Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t.sh
987 linesCodeBlameRaw
1import type { ActionsApi } from "./actions";
2import type { AiApi } from "./ai";
3import type { BillingAdminApi, BillingApi } from "./billing";
4import type { DeploymentsApi } from "./deployments";
5import type { ProjectsApi } from "./projects";
6import type { EventsApi } from "./events";
7import type { IdentityAdminApi, IdentityApi } from "./identity";
8import type { IntegrationsApi } from "./integrations";
9import type { PackagesApi } from "./packages";
10import type { WebhooksApi } from "./webhooks";
11import type { ReposApi } from "./repos";
12import type { PullDetail, WorkApi } from "./work";
13import type { Result } from "./result";
14import type { RunnersAdminApi, RunnersApi } from "./runners";
15
16/** A service binding, as far as these clients need it. */
17export type ServiceBinding = {
18 fetch(input: string, init?: RequestInit): Promise<Response>;
19};
20
21/**
22 * Calls a method on a service that speaks the JSON protocol used by the
23 * Rust services: `POST /rpc/<method>` with the arguments as the body.
24 */
25async function rpc<T>(
26 service: ServiceBinding,
27 method: string,
28 args: object,
29): Promise<T> {
30 // The hostname is ignored; a service binding always reaches its service.
31 const response = await service.fetch(`https://service/rpc/${method}`, {
32 method: "POST",
33 headers: { "content-type": "application/json" },
34 body: JSON.stringify(args),
35 });
36 if (!response.ok) {
37 throw new Error(`${method} failed with status ${response.status}`);
38 }
39 return (await response.json()) as T;
40}
41
42export function identityClient(service: ServiceBinding): IdentityApi {
43 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
44 return {
45 register: (username, email, password, inviteCode, client, emailProof) =>
46 call("register", {
47 username,
48 email,
49 password,
50 invite_code: inviteCode ?? null,
51 email_proof: emailProof ?? null,
52 client: client ?? null,
53 }),
54 signIn: (username, password, client) => call("sign_in", { username, password, client: client ?? null }),
55 twoFactorSignIn: (challenge, code, client) => call("two_factor_sign_in", { challenge, code, client: client ?? null }),
56 signOut: (sessionToken) => call("sign_out", { sessionToken }),
57 resendVerification: (user) => call("resend_verification", { user }),
58 verifyEmail: (token) => call("verify_email", { token }),
59 requestPasswordReset: (email, client) => call("request_password_reset", { email, client: client ?? null }),
60 resetPassword: (token, password) =>
61 call("reset_password", { token, password }),
62 deviceStart: (clientName) => call("device_start", { clientName }),
63 deviceLookup: (userCode) => call("device_lookup", { userCode }),
64 deviceResolve: (userCode, user, approve) =>
65 call("device_resolve", { userCode, user, approve }),
66 deviceClaim: (deviceCode) => call("device_claim", { deviceCode }),
67 oauthAuthorize: (user, approval) => call("oauth_authorize", { user, ...approval }),
68 oauthExchange: (code, codeVerifier, clientId, redirectUri) =>
69 call("oauth_exchange", { code, codeVerifier, clientId, redirectUri }),
70 oauthRefresh: (refreshToken, clientId) =>
71 call("oauth_refresh", { refreshToken, clientId }),
72 listOAuthGrants: (user) => call("list_oauth_grants", { user }),
73 revokeOAuthGrant: (user, id) => call("revoke_oauth_grant", { user, id }),
74 updateOAuthGrant: (user, id, grant) =>
75 call("update_oauth_grant", { user, id, scopes: grant.scopes }),
76 createWorkspace: (user, slug, name) => call("create_workspace", { user, slug, name }),
77 getWorkspace: (slug) => call("get_workspace", { slug }),
78 workspaceResidency: (slug) => call("workspace_residency", { slug }),
79 setWorkspaceResidency: (actor, slug, residency) => call("set_workspace_residency", { actor, slug, residency }),
80 listMembers: (slug, viewer) => call("list_members", { slug, viewer }),
81 addMember: (actor, slug, username) => call("add_member", { actor, slug, username }),
82 removeMember: (actor, slug, username) =>
83 call("remove_member", { actor, slug, username, surface: "web" }),
84 updateMember: (actor, slug, username, change) =>
85 call("update_member", { actor, slug, username, role: change.role ?? null, org_roles: change.org_roles ?? null, surface: "web" }),
86 transferOwnership: (actor, slug, username) => call("transfer_ownership", { actor, slug, username, surface: "web" }),
87 leaveWorkspace: (user, slug) => call("leave_workspace", { user, slug, surface: "web" }),
88 setMemberPrivileges: (actor, slug, change) => call("set_member_privileges", { actor, slug, privileges: change, surface: "web" }),
89 setTwoFactorRequirement: (actor, slug, required) =>
90 call("set_two_factor_requirement", { actor, slug, required, surface: "web" }),
91 updateWorkspace: (actor, slug, details) =>
92 call("update_workspace", { actor, slug, ...details }),
93 renameWorkspace: (actor, slug, newSlug) => call("rename_workspace", { actor, slug, newSlug }),
94 checkWorkspaceRename: (actor, slug, newSlug) =>
95 call("check_workspace_rename", { actor, slug, newSlug }),
96 resolveSlug: (slug) => call("resolve_slug", { slug }),
97 deleteWorkspace: (actor, slug, confirm) => call("delete_workspace", { actor, slug, confirm }),
98 checkWorkspaceDeletion: (actor, slug) => call("check_workspace_deletion", { actor, slug }),
99 setWorkspaceAvatar: (actor, slug, image) => call("set_workspace_avatar", { actor, slug, image }),
100 setUserAvatar: (user, image) => call("set_user_avatar", { user, image }),
101 listWorkspaceTokens: (slug, viewer) => call("list_workspace_tokens", { slug, viewer }),
102 removeWorkspaceToken: (actor, slug, id) =>
103 call("remove_workspace_token", { actor, slug, id }),
104 createToken: (actor, input) =>
105 call("create_token", {
106 actor,
107 owner: input.owner ?? null,
108 name: input.name,
109 description: input.description ?? null,
110 ttl_seconds: input.ttlSeconds,
111 workspace: input.workspace,
112 repository_selection: input.repositorySelection,
113 repositories: input.repositories,
114 permissions: input.permissions,
115 website: input.website ?? false,
116 }),
117 updateToken: (actor, id, change, owner) =>
118 call("update_token", {
119 actor,
120 id,
121 owner: owner ?? null,
122 name: change.name ?? null,
123 description: change.description ?? null,
124 repository_selection: change.repositorySelection ?? null,
125 repositories: change.repositories ?? null,
126 permissions: change.permissions ?? null,
127 website: change.website ?? null,
128 }),
129 regenerateToken: (actor, id, ttlSeconds, owner) =>
130 call("regenerate_token", { actor, id, owner: owner ?? null, ttl_seconds: ttlSeconds ?? null }),
131 getTokenPolicy: (slug, viewer) => call("get_token_policy", { slug, viewer }),
132 setTokenPolicy: (actor, slug, change) =>
133 call("set_token_policy", {
134 actor,
135 slug,
136 allow_tokens_for_all_workspaces: change.allowTokensForAllWorkspaces ?? null,
137 allow_tokens_for_this_workspace: change.allowTokensForThisWorkspace ?? null,
138 require_approval: change.requireApproval ?? null,
139 max_lifetime_days: change.maxLifetimeDays ?? null,
140 forbid_no_expiry: change.forbidNoExpiry ?? null,
141 surface: "web",
142 }),
143 listMemberTokens: (actor, slug, filter = {}) =>
144 call("list_member_tokens", { actor, slug, status: filter.status ?? null }),
145 reviewTokenRequest: (actor, slug, id, approve, reason) =>
146 call("review_token_request", { actor, slug, id, approve, reason: reason ?? null, surface: "web" }),
147 revokeMemberToken: (actor, slug, id, reason) =>
148 call("revoke_member_token", { actor, slug, id, reason: reason ?? null, surface: "web" }),
149 userForSession: (sessionToken) => call("user_for_session", { sessionToken }),
150 listInvites: (user) => call("list_invites", { user }),
151 createInvite: (user, invite) =>
152 call("create_invite", {
153 user,
154 email: invite.email,
155 message: invite.message ?? null,
156 join: invite.join ?? null,
157 join_role: invite.join ? (invite.joinRole ?? null) : null,
158 surface: "web",
159 }),
160 revokeInvite: (user, id) => call("revoke_invite", { user, id }),
161 resendInvite: (user, id) => call("resend_invite", { user, id }),
162 checkInvite: (code, client, options = {}) =>
163 call("check_invite", {
164 code,
165 client: client ?? null,
166 viewer: options.viewer ?? null,
167 any_status: options.anyStatus ?? false,
168 email_proof: options.emailProof ?? null,
169 }),
170 acceptInvite: (user, code) => call("accept_invite", { user, code }),
171 inviteMember: (actor, slug, who) =>
172 call("invite_member", { actor, slug, email: who.email ?? "", username: who.username ?? null, role: who.role ?? null, message: who.message ?? null }),
173 listInvitations: (user) => call("list_invitations", { user }),
174 acceptInvitation: (user, id) => call("accept_invitation", { user, id, surface: "web" }),
175 declineInvitation: (user, id) => call("decline_invitation", { user, id, surface: "web" }),
176 findPeople: (query, limit) => call("find_people", { query, limit: limit ?? null }),
177 workspaceInvites: (slug, viewer) => call("workspace_invites", { slug, viewer }),
178 revokeWorkspaceInvite: (actor, slug, id) => call("revoke_workspace_invite", { actor, slug, id }),
179 resendWorkspaceInvite: (actor, slug, id) => call("resend_workspace_invite", { actor, slug, id }),
180 userForGitCredentials: (username, secret) =>
181 call("user_for_git_credentials", { username, secret }),
182 userForAccessToken: (token) => call("user_for_access_token", { token }),
183 userForSshKey: (fingerprint) => call("user_for_ssh_key", { fingerprint }),
184 userByUsername: (username) => call("user_by_username", { username }),
185 usernames: (ids) => call("usernames", { ids }),
186 accounts: (ids) => call("accounts", { ids }),
187 usersForAudience: (ids) => call("users_for_audience", { ids }),
188 profile: (username) => call("profile", { username }),
189 updateProfile: (actor, fields) => call("update_profile", { actor, ...fields }),
190 profileWorkspaces: (username, viewer, publicIn) =>
191 call("profile_workspaces", { username, viewer, public: publicIn }),
192 dockPins: (user, workspace) => call("dock_pins", { user, workspace }),
193 setDockPins: (user, workspace, apps) => call("set_dock_pins", { user, workspace, apps }),
194 onboarding: (user, workspace) => call("onboarding", { user, workspace }),
195 setOnboarding: (user, workspace, change) => call("set_onboarding", { user, workspace, change }),
196 soundSettings: (user) => call("sound_settings", { user }),
197 setSoundSettings: (user, change) => call("set_sound_settings", { user, change }),
198 listSshKeys: (user) => call("list_ssh_keys", { user }),
199 addSshKey: (user, title, publicKey) =>
200 call("add_ssh_key", { user, title, publicKey }),
201 removeSshKey: (user, id) => call("remove_ssh_key", { user, id }),
202 listAccessTokens: (user) => call("list_access_tokens", { user }),
203 createAccessToken: (user, name, ttlSeconds, grant) =>
204 call("create_access_token", {
205 user,
206 name,
207 ttlSeconds,
208 scopes: grant?.scopes ?? null,
209 listed: grant?.listed ?? false,
210 }),
211 removeAccessToken: (user, id) => call("remove_access_token", { user, id }),
212 createRunCredential: (input) => call("create_run_credential", input),
213 bindRunCredentials: (tokenHashes, runId) => call("bind_run_credentials", { tokenHashes, runId }),
214 revokeRunCredentials: (target) => call("revoke_run_credentials", target),
215 // Who has access to a repository; see access.ts.
216 repoAccess: (owner, name, viewer) => call("repo_access", { viewer, path: { namespace: owner, name } }),
217 addCollaborator: (actor, owner, name, invitee, role) =>
218 call("add_collaborator", { actor, path: { namespace: owner, name }, invitee, role }),
219 setCollaboratorRole: (actor, owner, name, username, role) =>
220 call("set_collaborator_role", { actor, path: { namespace: owner, name }, username, role }),
221 removeCollaborator: (actor, owner, name, username) =>
222 call("remove_collaborator", { actor, path: { namespace: owner, name }, username }),
223 collaboratorPermission: (viewer, owner, name, username) =>
224 call("collaborator_permission", { viewer, path: { namespace: owner, name }, username }),
225 myRepoInvitations: (user) => call("my_repo_invitations", { user }),
226 respondRepoInvitation: (user, id, accept) => call("respond_repo_invitation", { user, id, accept }),
227 revokeRepoInvitation: (actor, owner, name, id) =>
228 call("revoke_repo_invitation", { actor, path: { namespace: owner, name }, id }),
229 setBasePermission: (actor, slug, base) => call("set_base_permission", { actor, slug, base_permission: base }),
230 outsideCollaborators: (viewer, slug) => call("outside_collaborators", { viewer, slug }),
231 // A repository's deploy keys; see deploy-keys.ts.
232 listDeployKeys: (viewer, owner, name) => call("list_deploy_keys", { viewer, path: { namespace: owner, name } }),
233 addDeployKey: (actor, owner, name, key) =>
234 call("add_deploy_key", { actor, path: { namespace: owner, name }, title: key.title, key: key.key, read_only: key.readOnly }),
235 removeDeployKey: (actor, owner, name, id) => call("remove_deploy_key", { actor, path: { namespace: owner, name }, id }),
236 // Teams; see teams.ts.
237 listTeams: (viewer, workspace, query) => call("list_teams", { viewer, workspace, query: query ?? null }),
238 getTeam: (viewer, workspace, team) => call("get_team", { viewer, workspace, team }),
239 createTeam: (actor, workspace, team) => call("create_team", { actor, workspace, ...team }),
240 setTeamCreation: (actor, slug, setting) => call("set_team_creation", { actor, slug, team_creation: setting }),
241 updateTeam: (actor, workspace, team, changes) => call("update_team", { actor, workspace, team, ...changes }),
242 deleteTeam: (actor, workspace, team) => call("delete_team", { actor, workspace, team }),
243 teamMembers: (viewer, workspace, team, includeChildTeams) =>
244 call("team_members", { viewer, workspace, team, include_child_teams: includeChildTeams ?? false }),
245 setTeamMember: (actor, workspace, team, username, role) =>
246 call("set_team_member", { actor, workspace, team, username, role }),
247 removeTeamMember: (actor, workspace, team, username) =>
248 call("remove_team_member", { actor, workspace, team, username }),
249 childTeams: (viewer, workspace, team) => call("child_teams", { viewer, workspace, team }),
250 teamRepos: (viewer, workspace, team) => call("team_repos", { viewer, workspace, team }),
251 setTeamRepo: (actor, workspace, team, owner, name, role) =>
252 call("set_team_repo", { actor, workspace, team, repo: { namespace: owner, name }, role }),
253 removeTeamRepo: (actor, workspace, team, owner, name) =>
254 call("remove_team_repo", { actor, workspace, team, repo: { namespace: owner, name } }),
255 userTeams: (viewer, workspace, username) => call("user_teams", { viewer, workspace, username }),
256 teamMemberships: (viewer, workspace) => call("team_memberships", { viewer, workspace }),
257 // People; see people.ts.
258 peopleDirectory: (viewer, workspace) => call("people_directory", { viewer, workspace }),
259 setMemberProfile: (actor, workspace, username, changes) => call("set_member_profile", { actor, workspace, username, ...changes }),
260 };
261}
262
263/**
264 * The slug a renamed workspace has now, for a `workspace.renamed` handler:
265 * asked of identity by the workspace's id, so that renames delivered twice
266 * or out of order converge. Falls back to the event's `to`.
267 */
268export async function currentWorkspaceSlug(
269 identity: ServiceBinding,
270 renamed: { workspaceId: string; to: string },
271): Promise<string> {
272 const names = await identityClient(identity).usernames([renamed.workspaceId]);
273 return names[renamed.workspaceId] ?? renamed.to;
274}
275
276/** The slugs whose rows move to `current`: the two a rename names, less `current`. */
277export function staleSlugs(renamed: { from: string; to: string }, current: string): string[] {
278 return [...new Set([renamed.from, renamed.to])].filter((slug) => slug !== current);
279}
280
281/**
282 * Where a transferred repository is now, as `namespace/name`, for a
283 * `repo.transferred` handler: asked of repos by id, so transfers delivered
284 * twice or out of order converge. Falls back to the event's destination.
285 */
286export async function currentRepoPath(
287 repos: ServiceBinding,
288 transferred: { repoId: string; name: string; to: string },
289): Promise<string> {
290 const path = await rpc<{ namespace: string; name: string } | null>(repos, "path_by_id", { id: transferred.repoId });
291 return path ? `${path.namespace}/${path.name}` : `${transferred.to}/${transferred.name}`;
292}
293
294/** The paths whose rows move to `current`: the two a transfer names, less `current`. */
295export function stalePaths(transferred: { name: string; from: string; to: string }, current: string): string[] {
296 return [...new Set([transferred.from, transferred.to].map((ns) => `${ns}/${transferred.name}`))].filter(
297 (path) => path !== current,
298 );
299}
300
301/**
302 * A repository's path change, from `repo.transferred` or `repo.renamed`,
303 * read the same way: the two paths (`namespace/name`) the event names, old
304 * then new. Null for any other event.
305 */
306export type RepoMove = { repoId: string; paths: [string, string] };
307
308export function repoMove(event: { type: string; data: unknown }): RepoMove | null {
309 const data = event.data as Record<string, string>;
310 if (event.type === "repo.transferred") {
311 return { repoId: data.repoId!, paths: [`${data.from}/${data.name}`, `${data.to}/${data.name}`] };
312 }
313 if (event.type === "repo.renamed") {
314 return { repoId: data.repoId!, paths: [`${data.namespace}/${data.from}`, `${data.namespace}/${data.to}`] };
315 }
316 return null;
317}
318
319/**
320 * Where a moved repository is now, as `namespace/name`: asked of repos by
321 * id, so moves delivered twice or out of order converge. Falls back to the
322 * event's new path.
323 */
324export async function currentMovedPath(repos: ServiceBinding, move: RepoMove): Promise<string> {
325 const path = await rpc<{ namespace: string; name: string } | null>(repos, "path_by_id", { id: move.repoId });
326 return path ? `${path.namespace}/${path.name}` : move.paths[1];
327}
328
329/** The paths whose rows move to `current`: the two a move names, less `current`. */
330export function staleMovedPaths(move: RepoMove, current: string): string[] {
331 return [...new Set(move.paths)].filter((path) => path !== current);
332}
333
334/** Staff-only identity. Only sudo binds to it; see `IdentityAdminApi`. */
335export function identityAdminClient(service: ServiceBinding): IdentityAdminApi {
336 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
337 return {
338 workspaces: (query) => call("admin_workspaces", { query: query ?? null }),
339 workspace: (slug) => call("admin_workspace", { slug }),
340 invites: (query, options = {}) => call("admin_invites", { query: query ?? null, to_g1t: options.toG1t ?? false }),
341 grantInvites: (username, amount, note, staff) => call("admin_grant_invites", { username, amount, note, staff }),
342 revokeInvite: (id, staff) => call("admin_revoke_invite", { id, staff }),
343 suspendUser: (name, suspend, reason, staff) => call("admin_suspend_user", { name, suspend, reason, staff }),
344 suspendWorkspace: (name, suspend, reason, staff) => call("admin_suspend_workspace", { name, suspend, reason, staff }),
345 blockedDomains: () => call("admin_blocked_domains", {}),
346 blockDomain: (domain, block, reason, staff) => call("admin_block_domain", { domain, block, reason, staff }),
347 deletedWorkspaces: () => call("admin_deleted_workspaces", {}),
348 restoreWorkspace: (workspaceId, staff) => call("admin_restore_workspace", { workspaceId, staff }),
349 purgeWorkspace: (workspaceId, staff, confirm) => call("admin_purge_workspace", { workspaceId, staff, confirm }),
350 aliases: () => call("admin_aliases", {}),
351 setAlias: (alias, workspace, note, staff) => call("admin_set_alias", { alias, workspace, note, staff }),
352 removeAlias: (alias, reason, staff) => call("admin_remove_alias", { alias, reason, staff }),
353 };
354}
355
356export function reposClient(service: ServiceBinding): ReposApi {
357 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
358 return {
359 get: (path, viewer) => call("get", { path, viewer }),
360 getById: (id, viewer) => call("get_by_id", { id, viewer }),
361 readable: (ids, viewer) => call("readable", { ids, viewer }),
362 publicNamespaces: (ownerId) => call("public_namespaces", { ownerId }),
363 list: (viewer, options = {}) => call("list", { viewer, ...options }),
364 create: (owner, input) => call("create", { owner, ...input }),
365 update: (actor, path, changes) => call("update", { actor, path, ...changes }),
366 transfer: (actor, path, to) => call("transfer", { actor, path, to }),
367 delete: (actor, path, confirm) => call("delete", { actor, path, confirm }),
368 deleted: (viewer, namespace) => call("deleted", { viewer, namespace }),
369 restore: (actor, path) => call("restore", { actor, path }),
370 purge: (actor, path, confirm) => call("purge", { actor, path, confirm }),
371 rename: (actor, path, name) => call("rename", { actor, path, name }),
372 archive: (actor, path, archived) => call("archive", { actor, path, archived }),
373 setVisibility: (actor, path, isPrivate, confirm) => call("set_visibility", { actor, path, isPrivate, confirm }),
374 setDefaultBranch: (actor, path, branch) => call("set_default_branch", { actor, path, branch }),
375 renameBranch: (actor, path, from, to) => call("rename_branch", { actor, path, from, to }),
376 createBranch: (actor, path, name, from = "") => call("create_branch", { actor, path, name, from }),
377 removeBranch: (actor, path, branch, head) => call("remove_branch", { actor, path, branch, head }),
378 resolveBranch: (repoId, branch) => call("resolve_branch", { repoId, branch }),
379 statusById: (id) => call("status_by_id", { id }),
380 storageOptions: () => call("storage_options", {}),
381 resolvePath: (path) => call("resolve_path", { path }),
382 tree: (path, viewer, ref, treePath) =>
383 call("tree", { path, viewer, ref, treePath }),
384 blob: (path, viewer, ref, filePath) =>
385 call("blob", { path, viewer, ref, filePath }),
386 log: (path, viewer, ref, limit) => call("log", { path, viewer, ref, limit }),
387 blame: (path, viewer, ref, filePath) => call("blame", { path, viewer, ref, filePath }),
388 forkForPull: (sourceId, pullId, actor) =>
389 call("fork_for_pull", { sourceId, pullId, actor }),
390 fork: (actor, path, input) => call("fork", { actor, path, ...input }),
391 forks: (path, viewer, limit) => call("forks", { path, viewer, limit: limit ?? null }),
392 syncFork: (actor, path, branch) => call("sync_fork", { actor, path, branch: branch ?? null }),
393 detachFork: (actor, path) => call("detach_fork", { actor, path }),
394 gitAccess: (path, viewer, service) =>
395 call("git_access", { path, viewer, service }),
396 branches: (path, viewer) => call("branches", { path, viewer }),
397 pathById: (id) => call("path_by_id", { id }),
398 lastCommits: (path, viewer, ref, treePath) => call("last_commits", { path, viewer, ref, treePath }),
399 branchDrift: (path, viewer, base, heads) => call("branch_drift", { path, viewer, base, heads }),
400 tags: (path, viewer) => call("tags", { path, viewer }),
401 about: (path, viewer) => call("about", { path, viewer }),
402 languages: (path, viewer) => call("languages", { path, viewer }),
403 contributors: (path, viewer) => call("contributors", { path, viewer }),
404 license: (path, viewer) => call("license", { path, viewer }),
405 stars: (path, viewer) => call("stars", { path, viewer }),
406 star: (actor, path, starred) => call("star", { path, actor, starred }),
407 stargazers: (path, viewer, page) => call("stargazers", { path, viewer, page: page ?? null }),
408 starred: (username, viewer) => call("starred", { username, viewer }),
409 releases: (path, viewer) => call("releases", { path, viewer }),
410 release: (path, viewer, which) => call("release", { path, viewer, id: which.id ?? null, tag: which.tag ?? null, latest: which.latest ?? false }),
411 createRelease: (actor, path, release) => call("create_release", { path, actor, ...release }),
412 updateRelease: (actor, path, id, change) => call("update_release", { path, actor, id, ...change }),
413 deleteRelease: (actor, path, id) => call("delete_release", { path, actor, id }),
414 listFiles: (repoId, ref, limit, options) => call("list_files", { repoId, ref, skipDirs: [], limit, links: options?.links ?? false }),
415 openArchiveToken: (path, token) => call("open_archive_token", { path, token }),
416 rawBlobs: (repoId, hashes, maxBytes) => call("raw_blobs", { repoId, hashes, maxBytes }),
417 rawFile: (repoId, ref, path, maxBytes) => call("raw_file", { repoId, ref, path, maxBytes }),
418 commitFile: (repo, actor, file) => call("commit_file", { repo, actor, ...file }),
419 land: (sourceId, actor, branch) => call("land", { sourceId, actor, branch }),
420 compare: (repoId, viewer, base, head, baseBranch, paths, targetId) =>
421 call("compare", { repoId, viewer, base, head, baseBranch, paths: paths ?? null, ...(targetId ? { targetId } : {}) }),
422 claimBackups: (limit, maxRunning) => call("claim_backups", { limit, maxRunning }),
423 // The sandbox's own calls are snake_case (they come through the API).
424 failBackup: (jobId, token, error) => call("backup_fail", { job_id: jobId, token, error }),
425 };
426}
427
428/**
429 * `PullDetail`'s own fields that the work service writes in snake_case:
430 * `g1t_contracts::work::PullDetail` has no camelCase renaming, though what
431 * it holds (`Pull`, `CheckRun` and the rest) does. Each with its name here.
432 */
433const PULL_DETAIL_FIELDS = [
434 ["earlier_checks", "earlierChecks"],
435 ["required_checks", "requiredChecks"],
436 ["code_owners", "codeOwners"],
437] as const;
438
439/**
440 * A pull request's detail as the work service sent it, with its own fields
441 * in the camelCase this package uses: read at the edge, by `workClient`'s
442 * `getPull`. Either spelling is taken, so a service that already sends
443 * camelCase reads the same.
444 */
445export function pullDetailFromWire(raw: Record<string, unknown>): PullDetail {
446 const detail: Record<string, unknown> = { ...raw };
447 for (const [snake, camel] of PULL_DETAIL_FIELDS) {
448 if (snake in detail) {
449 if (!(camel in detail)) detail[camel] = detail[snake];
450 delete detail[snake];
451 }
452 }
453 return detail as PullDetail;
454}
455
456export function workClient(service: ServiceBinding): WorkApi {
457 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
458 return {
459 openIssue: (actor, repo, input) => call("open_issue", { actor, repo, ...input }),
460 listIssues: (repo, viewer, filter = {}) => call("list_issues", { repo, viewer, ...filter }),
461 getIssue: (repo, number, viewer) => call("get_issue", { repo, number, viewer }),
462 closedByCommit: (repo, commit, viewer) => call("closed_by_commit", { repo, commit, viewer }),
463 updateIssue: (actor, repo, number, input) =>
464 call("update_issue", { actor, repo, number, ...input }),
465 closeIssue: (actor, repo, number, reason) =>
466 call("close_issue", { actor, repo, number, reason }),
467 reopenIssue: (actor, repo, number) => call("reopen_issue", { actor, repo, number }),
468 listLabels: (repo, viewer) => call("list_labels", { repo, viewer }),
469 saveLabel: (actor, repo, label) => call("save_label", { actor, repo, ...label }),
470 deleteLabel: (actor, repo, name) => call("delete_label", { actor, repo, name }),
471 addDefaultLabels: (actor, repo) => call("add_default_labels", { actor, repo }),
472 setLabels: (actor, repo, number, labels, change = "set") =>
473 call("set_labels", { actor, repo, number, labels, change }),
474 listMilestones: (repo, viewer, state) => call("list_milestones", { repo, viewer, state }),
475 getMilestone: (repo, number, viewer) => call("get_milestone", { repo, number, viewer }),
476 saveMilestone: (actor, repo, milestone) => call("save_milestone", { actor, repo, ...milestone }),
477 deleteMilestone: (actor, repo, number) => call("delete_milestone", { actor, repo, number }),
478 counts: (repo, viewer) => call("counts", { repo, viewer }),
479 addComment: (actor, repo, number, comment) =>
480 call("add_comment", { actor, repo, number, ...comment }),
481 editComment: (actor, repo, commentId, body) => call("edit_comment", { actor, repo, commentId, body }),
482 deleteComment: (actor, repo, commentId) => call("delete_comment", { actor, repo, commentId }),
483 react: (actor, repo, number, reaction) => call("react", { actor, repo, number, ...reaction }),
484 reportChecks: (runId, token, report) =>
485 call("report_checks", { runId, token, ...report }),
486 startMergecheck: (pullId) => call("start_mergecheck", { pullId }),
487 failMergecheck: (pullId, token, error) => call("report_mergecheck", { pullId, token, error }),
488 advance: (pullId) => call("advance", { pullId }),
489 managedPulls: (repoId) => call("managed_pulls", { repoId }),
490 queue: (repo, viewer) => call("queue", { repo, viewer }),
491 queueBuild: (repoId) => call("queue_build", { repoId }),
492 failQueue: (entryId, token, error) => call("report_queue", { entryId, token, error }),
493 removeFromQueue: (actor, repo, number) => call("remove_from_queue", { actor, repo, number }),
494 getSettings: (repo, viewer) => call("get_settings", { repo, viewer }),
495 // Rulesets travel in snake_case (rules.ts).
496 listRulesets: (owner, viewer, includeParents = false) =>
497 call("list_rulesets", { viewer, ...owner, include_parents: includeParents }),
498 getRuleset: (owner, id, viewer) => call("get_ruleset", { viewer, ...owner, id }),
499 saveRuleset: (actor, owner, ruleset, id) => call("save_ruleset", { actor, ...owner, id: id ?? null, ruleset }),
500 deleteRuleset: (actor, owner, id) => call("delete_ruleset", { actor, ...owner, id }),
501 effectiveRules: (repo, name, viewer, target = "branch") => call("effective_rules", { viewer, repo, name, target }),
502 ruleEvaluations: (owner, viewer, filter = {}) => call("rule_evaluations", { viewer, ...owner, ...filter }),
503 seenChecks: (repo, viewer) => call("seen_checks", { repo, viewer }),
504 commitChecks: (repo, viewer, shas) => call("commit_checks", { repo, viewer, shas }),
505 getCheckRun: (repo, id, viewer) => call("get_check_run", { repo, id, viewer }),
506 checkRunAnnotations: (repo, id, viewer) => call("check_run_annotations", { repo, id, viewer }),
507 requestCheckAction: (actor, repo, id, identifier) => call("request_check_action", { actor, repo, id, identifier }),
508 rerequestCheckRun: (actor, repo, id) => call("rerequest_check_run", { actor, repo, id }),
509 codeownersErrors: (repo, viewer, ref) => call("codeowners_errors", { repo, viewer, ref: ref ?? null }),
510 updateSettings: (actor, repo, settings) =>
511 call("update_settings", { actor, repo, settings }),
512 openPull: (actor, repo, input) => call("open_pull", { actor, repo, ...input }),
513 listPulls: (repo, viewer, state, filter = {}) => call("list_pulls", { repo, viewer, state, ...filter }),
514 deliveryInsights: (repoIds, viewer, from, until) => call("delivery_insights", { repoIds, viewer, from, until }),
515 pullsForRepos: (repoIds, viewer, limit) => call("pulls_for_repos", { repoIds, viewer, limit }),
516 // Its own fields arrive in snake_case: read into camelCase here.
517 getPull: (repo, number, viewer) =>
518 call<Result<Record<string, unknown>>>("get_pull", { repo, number, viewer }).then(
519 (found): Result<PullDetail> => (found.ok ? { ok: true, value: pullDetailFromWire(found.value) } : found),
520 ),
521 updatePull: (actor, repo, number, changes) =>
522 call("update_pull", { actor, repo, number, ...changes }),
523 catchUpPull: (actor, repo, number, options = {}) => call("catch_up_pull", { actor, repo, number, ...options }),
524 setAutoMerge: (actor, repo, number, enabled, options = {}) =>
525 call("set_auto_merge", { actor, repo, number, enabled, ...options }),
526 mergeChoices: (viewer, repo, number) => call("merge_choices", { viewer, repo, number }),
527 deleteHeadBranch: (actor, repo, number) => call("delete_head_branch", { actor, repo, number }),
528 restoreHeadBranch: (actor, repo, number) => call("restore_head_branch", { actor, repo, number }),
529 commitComments: (viewer, repo, commit, page) =>
530 call("commit_comments", { viewer, repo, commit: commit ?? null, page: page ?? null }),
531 addCommitComment: (actor, repo, commit, body, at) =>
532 call("add_commit_comment", { actor, repo, commit, body, path: at?.path ?? null, line: at?.line ?? null }),
533 editCommitComment: (actor, repo, id, body) => call("edit_commit_comment", { actor, repo, id, body }),
534 deleteCommitComment: (actor, repo, id) => call("delete_commit_comment", { actor, repo, id }),
535 readyPull: (actor, repo, number, summary) =>
536 call("ready_pull", { actor, repo, number, summary }),
537 closePull: (actor, repo, number) => call("close_pull", { actor, repo, number }),
538 reopenPull: (actor, repo, number) => call("reopen_pull", { actor, repo, number }),
539 convertPullToDraft: (actor, repo, number) => call("convert_pull_to_draft", { actor, repo, number }),
540 mergePull: (actor, repo, number, options = {}) =>
541 call("merge_pull", { actor, repo, number, ...options }),
542 listActivePulls: (viewer) => call("list_active_pulls", { viewer }),
543 byAuthor: (username, viewer, filter = {}) => call("by_author", { username, viewer, ...filter }),
544 contributions: (username, viewer) => call("contributions", { username, viewer }),
545 appendSession: (actor, repo, number, entries) =>
546 call("append_session", { actor, repo, number, entries }),
547 readSession: (repo, number, viewer, afterSeq = 0) =>
548 call("read_session", { repo, number, viewer, afterSeq }),
549 // Coordination: harness sessions, claims, an issue's whole context and
550 // decision records. Their arguments are snake_case, as the Rust service
551 // reads them; what comes back is camelCase.
552 getWork: (repo, number, viewer) => call("get_work", { repo, number, viewer }),
553 listClaims: (repo, viewer, filter = {}) =>
554 call("list_claims", { repo, viewer, state: filter.state ?? null, issue: filter.issue ?? null }),
555 listWorkSessions: (repo, viewer, filter = {}) =>
556 call("list_work_sessions", {
557 repo,
558 viewer,
559 state: filter.state ?? null,
560 issue: filter.issue ?? null,
561 pull: filter.pull ?? null,
562 path: filter.path ?? null,
563 subagents: filter.subagents ?? false,
564 }),
565 getWorkSession: (repo, id, viewer, afterSeq = 0) =>
566 call("get_work_session", { repo, id, viewer, after_seq: afterSeq }),
567 pullSessions: (repo, viewer, numbers) => call("pull_sessions", { repo, viewer, numbers }),
568 listDecisions: (repo, number, viewer) => call("list_decisions", { repo, number, viewer }),
569 };
570}
571
572export function billingClient(service: ServiceBinding): BillingApi {
573 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
574 return {
575 status: () => call("status", {}),
576 account: (workspace, viewer) => call("account", { workspace, viewer }),
577 ledger: (workspace, viewer) => call("ledger", { workspace, viewer }),
578 credits: (workspace, viewer) => call("credits", { workspace, viewer }),
579 statement: (workspace, viewer, month = null, group = "day") => call("statement", { workspace, viewer, month, group }),
580 statementEntries: (workspace, viewer, filter) =>
581 call("statement_entries", {
582 workspace,
583 viewer,
584 month: filter.month,
585 kind: filter.kind,
586 day: filter.day ?? null,
587 project: filter.project ?? null,
588 before: filter.before ?? null,
589 }),
590 usage: (workspace, viewer, since) => call("usage", { workspace, viewer, since }),
591 checkout: (actor, workspace, amountCents, returnUrl, method = "card") =>
592 call("checkout", { actor, workspace, amountCents, returnUrl, method }),
593 confirm: (workspace, viewer, session) => call("confirm", { workspace, viewer, session }),
594 trial: (workspace, exempt) => call("trial", { workspace, exempt }),
595 features: (workspace, viewer) => call("features", { workspace, viewer }),
596 subscribe: (actor, workspace, feature, returnUrl) =>
597 call("subscribe", { actor, workspace, feature, returnUrl }),
598 confirmSubscription: (workspace, viewer, session) =>
599 call("confirm_subscription", { workspace, viewer, session }),
600 cancelSubscription: (actor, workspace, feature, resume = false) =>
601 call("cancel_subscription", { actor, workspace, feature, resume }),
602 convertToPaid: (actor, workspace, returnUrl) => call("convert_to_paid", { actor, workspace, returnUrl }),
603 hasFeature: (workspace, feature) => call("has_feature", { workspace, feature }),
604 freeWorkspaces: (workspaces) => call("free_workspaces", { workspaces }),
605 chargeFeature: (charge) => call("charge_feature", charge),
606 billingPortal: (actor, workspace, returnUrl) => call("billing_portal", { actor, workspace, return_url: returnUrl }),
607 recordSandbox: (usage) => call("record_sandbox", usage),
608 limit: (workspace, viewer) => call("limit", { workspace, viewer }),
609 checkLimit: (workspace) => call("check_limit", { workspace }),
610 prices: () => call("prices", {}),
611 notePending: (workspace, source, costMicros, detail = null, month = null) =>
612 call("note_pending", { workspace, source, costMicros, detail, ...(month ? { month } : {}) }),
613 usageMeters: (workspace, viewer) => call("usage_meters", { workspace, viewer }),
614 setSpendLimit: (actor, workspace, spendLimitMicros, useFullLimit = false, raiseOnce = false) =>
615 call("set_spend_limit", { actor, workspace, spendLimitMicros, use_full_limit: useFullLimit, raise_once: raiseOnce }),
616 invoices: (workspace, viewer) => call("invoices", { workspace, viewer }),
617 entitlements: (workspace) => call("entitlements", { workspace }),
618 reserve: (reservation) => call("reserve", reservation),
619 settle: (reservationId, actualMicros) => call("settle", { reservationId, actualMicros }),
620 cardCheck: (actor, workspace, returnUrl) => call("card_check", { actor, workspace, returnUrl }),
621 confirmCardCheck: (workspace, viewer, session) => call("confirm_card_check", { workspace, viewer, session }),
622 requestLimit: (actor, workspace, request) => call("request_limit", { actor, workspace, ...request }),
623 limitRequests: (workspace, viewer) => call("limit_requests", { workspace, viewer }),
624 confirmSpike: (actor, workspace, keepGoing) => call("confirm_spike", { actor, workspace, keepGoing }),
625 usageReport: (workspace, viewer, range) =>
626 call("usage_report", { workspace, viewer, from: range.from, until: range.until, products: range.products ?? [], projects: range.projects ?? [] }),
627 setBudget: (actor, workspace, budget) => call("set_budget", { actor, workspace, ...budget }),
628 billingDetails: (workspace, viewer) => call("billing_details", { workspace, viewer }),
629 setBillingDetails: (actor, workspace, details) => call("set_billing_details", { actor, workspace, ...details }),
630 };
631}
632
633export function billingAdminClient(service: ServiceBinding): BillingAdminApi {
634 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
635 return {
636 accounts: (query) => call("admin_accounts", { query: query ?? null }),
637 account: (id) => call("admin_account", { id }),
638 setTerms: (id, terms, by) => call("admin_set_terms", { id, terms, by }),
639 setAllowances: (id, allowances, note, by) => call("admin_set_allowances", { id, allowances, note, by }),
640 complimentary: (workspace) => call("admin_complimentary", { workspace }),
641 setComplimentary: (workspace, terms, note, by) =>
642 call("admin_set_complimentary", {
643 workspace,
644 allowance_micros: terms.allowanceMicros,
645 unlimited: terms.unlimited,
646 fee_cents: terms.feeCents,
647 charge_past_allowance: terms.chargePastAllowance,
648 note,
649 by,
650 }),
651 endComplimentary: (workspace, note, by) => call("admin_end_complimentary", { workspace, note, by }),
652 createEnterprise: (name, workspaces, by) => call("admin_create_enterprise", { name, workspaces, by }),
653 attach: (workspace, account, by) => call("admin_attach", { workspace, account, by }),
654 credit: (workspace, amountMicros, note, by, options = { kind: "goodwill" }) =>
655 call("admin_credit", {
656 workspace,
657 amount_micros: amountMicros,
658 note,
659 by,
660 kind: options.kind,
661 expires_at: options.expiresAt ?? null,
662 refund_for: options.refundFor ?? null,
663 refund_day: options.refundDay ?? null,
664 }),
665 credits: (filter = {}) =>
666 call("admin_credits", {
667 workspace: filter.workspace ?? null,
668 kind: filter.kind ?? null,
669 month: filter.month ?? null,
670 by: filter.by ?? null,
671 }),
672 revokeCredit: (id, note, by) => call("admin_revoke_credit", { id, note, by }),
673 resetBilling: (workspace, confirm, note, by) => call("admin_reset_billing", { workspace, confirm, note, by }),
674 detachTestStripe: (a) =>
675 call("admin_detach_test_stripe", {
676 workspace: a.workspace ?? null,
677 exclude: a.exclude ?? null,
678 dry_run: a.dryRun,
679 cancel_at_stripe: a.cancelAtStripe ?? false,
680 confirm: a.confirm ?? "",
681 by: a.by,
682 }),
683 billingLink: (workspace, by) => call("admin_billing_link", { workspace, by }),
684 stripe: (fix = false, by) => call("admin_stripe", { fix, by: by ?? null }),
685 enterpriseBilling: (id, email, by) => call("admin_enterprise_billing", { id, email, by }),
686 enterpriseAddress: (id, address, taxIdType, taxId, by) => call("admin_enterprise_address", { id, address, taxIdType, taxId, by }),
687 invoiceEnterprise: (id, by) => call("admin_invoice_enterprise", { id, by }),
688 accountsFor: (workspaces) => call("admin_accounts", { query: null, workspaces }),
689 signals: () => call("admin_signals", {}),
690 overview: () => call("admin_overview", {}),
691 sales: (workspace) => call("admin_sales", { workspace }),
692 setSales: (workspace, record, by) =>
693 call("admin_set_sales", {
694 workspace,
695 stage: record.stage,
696 owner: record.owner ?? null,
697 next_step: record.nextStep ?? null,
698 next_at: record.nextAt ?? null,
699 by,
700 }),
701 addNote: (workspace, text, by) => call("admin_add_note", { workspace, text, by }),
702 workspaceInvoices: (workspace) => call("admin_workspace_invoices", { workspace }),
703 allInvoices: (filter = {}) => call("admin_invoices", { status: filter.status ?? null, month: filter.month ?? null }),
704 audit: (filter = {}) =>
705 call("admin_audit", { by: filter.by ?? null, action: filter.action ?? null, before: filter.before ?? null }),
706 limitRequests: (status = "open") => call("admin_limit_requests", { status }),
707 decideLimitRequest: (id, decision, amountMicros, note, by) =>
708 call("admin_decide_limit_request", { id, decision, amount_micros: amountMicros, note, by }),
709 overages: () => call("admin_overages", {}),
710 goodwill: (workspace, amountMicros, reason, by, day = null, requestKey = null) =>
711 call("admin_goodwill", { workspace, amount_micros: amountMicros, reason, by, day, request_key: requestKey }),
712 velocity: () => call("admin_velocity", {}),
713 recordPayment: (workspace, amountMicros, reference, note, by) =>
714 call("admin_record_payment", { workspace, amount_micros: amountMicros, reference, note, by }),
715 costs: (days) => call("admin_costs", { days: days ?? null }),
716 costAlerts: () => call("admin_cost_alerts", {}),
717 spendCaps: () => call("admin_spend_caps", {}),
718 liftBreaker: (note, by) => call("admin_lift_breaker", { note, by }),
719 platformGuard: () => call("admin_platform_guard", {}),
720 setPause: (level, paused, note, by) => call("admin_set_pause", { level, paused, note, by }),
721 decideProposal: (id, decision, note, by) => call("admin_decide_proposal", { id, decision, note, by }),
722 setCostSettings: (settings, by) => call("admin_set_cost_settings", { settings, by }),
723 setCostMapping: (mapping, by) =>
724 call("admin_set_cost_mapping", {
725 product: mapping.product,
726 meter: mapping.meter,
727 bucket: mapping.bucket ?? "",
728 price_meter: mapping.priceMeter ?? null,
729 own_meter: mapping.ownMeter ?? null,
730 scale_to_own: mapping.scaleToOwn ?? false,
731 drift_percent: mapping.driftPercent ?? null,
732 note: mapping.note ?? "",
733 remove: mapping.remove ?? false,
734 by,
735 }),
736 runCosts: (by) => call("admin_run_costs", { by }),
737 };
738}
739
740export function eventsClient(service: ServiceBinding): EventsApi {
741 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
742 return {
743 publish: (events) => call("publish", { events }),
744 list: (query) => call("list", query),
745 activityDigest: (args) => call("activity_digest", args),
746 };
747}
748
749export function integrationsClient(service: ServiceBinding): IntegrationsApi {
750 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
751 return {
752 list: (workspace, viewer) => call("list", { workspace, viewer }),
753 connect: (actor, workspace, input) => call("connect", { actor, workspace, ...input }),
754 update: (actor, workspace, id, input) => call("update", { actor, workspace, id, ...input }),
755 disconnect: (actor, workspace, id) => call("disconnect", { actor, workspace, id }),
756 test: (actor, workspace, id) => call("test", { actor, workspace, id }),
757 deliveries: (workspace, viewer, id) => call("deliveries", { workspace, viewer, id }),
758 resolve: (workspace, viewer, reference) => call("resolve", { workspace, viewer, reference }),
759 import: (actor, repo, reference) => call("import", { actor, repo, reference }),
760 links: (repo, number) => call("links", { repo, number }),
761 };
762}
763
764/**
765 * A workspace's AI providers and Ask g1t. Kept by the integrations service,
766 * so it is built on the same binding, with its own methods.
767 */
768export function aiClient(service: ServiceBinding): AiApi {
769 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
770 return {
771 list: (workspace, viewer) => call("ai_list", { workspace, viewer }),
772 add: (actor, workspace, input) => call("ai_add", { actor, workspace, ...input }),
773 update: (actor, workspace, id, input) => call("ai_update", { actor, workspace, id, ...input }),
774 remove: (actor, workspace, id) => call("ai_remove", { actor, workspace, id }),
775 test: (actor, workspace, id) => call("ai_test", { actor, workspace, id }),
776 askSettings: (workspace, viewer) => call("ask_settings", { workspace, viewer }),
777 setAskSettings: (actor, workspace, providerId, model) =>
778 call("set_ask_settings", { actor, workspace, provider_id: providerId, model }),
779 // Streamed: the response itself, not its parsed body.
780 ask: (actor, workspace, messages, page, signal) =>
781 service.fetch("https://service/rpc/ask", {
782 method: "POST",
783 headers: { "content-type": "application/json" },
784 body: JSON.stringify({ actor, workspace, messages, page }),
785 signal,
786 }),
787 };
788}
789
790export function webhooksClient(service: ServiceBinding): WebhooksApi {
791 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
792 return {
793 list: (viewer, owner) => call("list", { viewer, ...owner }),
794 create: (actor, owner, input) => call("create", { actor, ...owner, ...input }),
795 update: (actor, owner, id, input) => call("update", { actor, ...owner, id, ...input }),
796 delete: (actor, owner, id) => call("delete", { actor, ...owner, id }),
797 ping: (actor, owner, id) => call("ping", { actor, ...owner, id }),
798 deliveries: (viewer, owner, id) => call("deliveries", { viewer, ...owner, id }),
799 redeliver: (actor, owner, deliveryId) => call("redeliver", { actor, ...owner, deliveryId }),
800 };
801}
802
803export function actionsClient(service: ServiceBinding): ActionsApi {
804 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
805 return {
806 workflows: (repo, viewer) => call("workflows", { repo, viewer }),
807 runs: (repo, viewer, filter = {}) => call("runs", { repo, viewer, ...filter }),
808 run: (repo, viewer, id, attempt) => call("run", { repo, viewer, id, attempt: attempt ?? null }),
809 logs: (repo, viewer, job, after = 0) => call("logs", { repo, viewer, job, after }),
810 summaries: (repo, viewer, id, attempt) => call("summaries", { repo, viewer, id, attempt: attempt ?? null }),
811 jobLogText: (repo, viewer, job) => call("job_log_text", { repo, viewer, job }),
812 runLogs: (repo, viewer, id, attempt) => call("run_logs", { repo, viewer, id, attempt: attempt ?? null }),
813 dispatch: (actor, repo, workflow, ref, inputs) => call("dispatch", { actor, repo, workflow, ref, inputs }),
814 cancel: (actor, repo, id, force = false) => call("cancel", { actor, repo, id, force }),
815 rerun: (actor, repo, id, failedOnly = false, options = {}) =>
816 call("rerun", { actor, repo, id, failed_only: failedOnly, job: options.job ?? null, debug: options.debug ?? false }),
817 setWorkflowEnabled: (actor, repo, workflow, enabled) =>
818 call("set_workflow_enabled", { actor, repo, workflow, enabled }),
819 settings: (actor, owner, kind) => call("settings", { actor, ...owner, kind }),
820 setSetting: (actor, owner, kind, name, value, options = {}) =>
821 call("set_setting", { actor, ...owner, kind, name, value, ...options }),
822 deleteSetting: (actor, owner, kind, name, id) => call("delete_setting", { actor, ...owner, kind, name, id }),
823 approveRun: (actor, repo, id) => call("approve_run", { actor, repo, id }),
824 pendingDeployments: (repo, viewer, id) => call("pending_deployments", { repo, viewer, id }),
825 reviewDeployments: (actor, repo, id, state, environments = [], comment) =>
826 call("review_deployments", { actor, repo, id, state, environments, comment: comment ?? null }),
827 actionsSettings: (repo, viewer) => call("actions_settings", { repo, viewer }),
828 setActionsSettings: (actor, repo, change) => call("set_actions_settings", { actor, repo, ...change }),
829 workspaceActionsSettings: (workspace, viewer) => call("workspace_actions_settings", { workspace, viewer }),
830 setWorkspaceActionsSettings: (actor, workspace, change) =>
831 call("set_workspace_actions_settings", { actor, workspace, ...change }),
832 workspaceManagedWorkflows: (workspace, viewer) => call("workspace_managed_workflows", { workspace, viewer }),
833 setWorkspaceManagedWorkflow: (actor, workspace, name, change, create = false) =>
834 call("set_workspace_managed_workflow", { actor, workspace, name, create, ...change }),
835 removeWorkspaceManagedWorkflow: (actor, workspace, name) =>
836 call("remove_workspace_managed_workflow", { actor, workspace, name }),
837 environments: (repo, viewer) => call("environments", { repo, viewer }),
838 setEnvironment: (actor, repo, name, change) => call("set_environment", { actor, repo, name, ...change }),
839 deleteEnvironment: (actor, repo, name) => call("delete_environment", { actor, repo, name }),
840 artifacts: (repo, viewer, filter = {}) => call("artifacts", { repo, viewer, ...filter }),
841 artifactDownload: (repo, viewer, by) => call("artifact_download", { repo, viewer, ...by }),
842 deleteArtifact: (actor, repo, id) => call("delete_artifact", { actor, repo, id }),
843 artifactRetention: (repo, viewer, days) => call("artifact_retention", { repo, viewer, days }),
844 };
845}
846
847
848/** Staff-only self-hosted runners, on the actions service: only sudo calls it. */
849export function runnersAdminClient(service: ServiceBinding): RunnersAdminApi {
850 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
851 return {
852 list: (workspace) => call("admin_runners", { workspace }),
853 remove: (workspace, id, staff) => call("admin_remove_runners", { workspace, id, staff }),
854 };
855}
856
857/** Self-hosted runners, kept by the actions service. */
858export function runnersClient(service: ServiceBinding): RunnersApi {
859 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
860 return {
861 stuck: (viewer) => call("stuck_jobs", { viewer }),
862 activity: (actor, workspace) => call("runner_activity", { actor, workspace }),
863 list: (actor, owner) => call("runners", { actor, ...owner }),
864 createToken: (actor, owner, group) => call("create_registration_token", { actor, ...owner, group }),
865 remove: (actor, owner, id) => call("remove_runner", { actor, ...owner, id }),
866 groups: (actor, workspace) => call("runner_groups", { actor, workspace }),
867 setGroup: (actor, workspace, group) => call("set_runner_group", { actor, workspace, ...group }),
868 deleteGroup: (actor, workspace, id) => call("delete_runner_group", { actor, workspace, id }),
869 settings: (actor, owner) => call("runner_settings", { actor, ...owner }),
870 setSettings: (actor, owner, change) => call("set_runner_settings", { actor, ...owner, ...change }),
871 reportDesktop: (actor, report) => call("report_desktop", { actor, ...report }),
872 desktops: (actor, workspace) => call("desktop_runners", { actor, workspace }),
873 };
874}
875
876export function deploymentsClient(service: ServiceBinding): DeploymentsApi {
877 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
878 return {
879 settings: (project, viewer) => call("settings", { project, viewer }),
880 updateSettings: (actor, project, changes) => call("update_settings", { actor, project, changes }),
881 list: (project, viewer) => call("list", { project, viewer }),
882 get: (project, id, viewer) => call("get", { project, id, viewer }),
883 redeploy: (actor, project, branch) => call("redeploy", { actor, project, branch }),
884 takeDown: (actor, project, branch) => call("take_down", { actor, project, branch }),
885 overview: (workspace, viewer) => call("overview", { workspace, viewer }),
886 usage: (workspace, viewer) => call("usage", { workspace, viewer }),
887 domains: (project, viewer) => call("domains", { project, viewer }),
888 addDomain: (actor, project, hostname, options = {}) =>
889 call("add_domain", { actor, project, hostname, twin: !!options.twin }),
890 removeDomain: (actor, project, id) => call("remove_domain", { actor, project, id }),
891 refreshDomain: (actor, project, id) => call("refresh_domain", { actor, project, id }),
892 repoDeployments: (repo, viewer, filter = {}) => call("list_deployments", { repo, viewer, ...filter }),
893 repoDeployment: (repo, id, viewer) => call("get_deployment", { repo, id, viewer }),
894 environments: (repo, viewer) => call("list_environments", { repo, viewer }),
895 createDeployment: (actor, repo, input) => call("create_deployment", { repo, actor, ...input }),
896 createDeploymentStatus: (actor, repo, id, input) => call("create_deployment_status", { repo, actor, id, ...input }),
897 shipped: (workspace, viewer, repos) => call("shipped", { workspace, viewer, repos }),
898 };
899}
900
901/** Packages: the registries beside the code (services/packages). */
902export function packagesClient(service: ServiceBinding): PackagesApi {
903 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
904 return {
905 list: (workspace, viewer, filter = {}) =>
906 call("list_packages", {
907 workspace,
908 viewer,
909 ecosystem: filter.ecosystem ?? null,
910 repo_id: filter.repoId ?? null,
911 query: filter.query ?? null,
912 }),
913 get: (workspace, ecosystem, name, viewer) => call("get_package", { workspace, ecosystem, name, viewer }),
914 deleteVersion: (actor, workspace, ecosystem, name, version, surface) =>
915 call("delete_version", { actor, workspace, ecosystem, name, version, surface: surface ?? null }),
916 deletePackage: (actor, workspace, ecosystem, name, surface) =>
917 call("delete_package", { actor, workspace, ecosystem, name, surface: surface ?? null }),
918 set: (actor, workspace, ecosystem, name, change, surface) =>
919 call("set_package", {
920 actor,
921 workspace,
922 ecosystem,
923 name,
924 visibility: change.visibility ?? null,
925 link: change.link ?? null,
926 unlink: change.unlink ?? false,
927 inherit_access: change.inheritAccess ?? null,
928 surface: surface ?? null,
929 }),
930 settings: (workspace, ecosystem, name, viewer) => call("package_settings", { workspace, ecosystem, name, viewer }),
931 deleted: (workspace, viewer) => call("deleted_packages", { workspace, viewer }),
932 restorePackage: (actor, workspace, ecosystem, name, surface) =>
933 call("restore_package", { actor, workspace, ecosystem, name, surface: surface ?? null }),
934 restoreVersion: (actor, workspace, ecosystem, name, version, surface) =>
935 call("restore_version", { actor, workspace, ecosystem, name, version, surface: surface ?? null }),
936 setAccess: (actor, workspace, ecosystem, name, who, role, surface) =>
937 call("set_package_access", {
938 actor,
939 workspace,
940 ecosystem,
941 name,
942 user: "user" in who ? who.user : null,
943 team: "team" in who ? who.team : null,
944 role,
945 surface: surface ?? null,
946 }),
947 removeAccess: (actor, workspace, ecosystem, name, who, surface) =>
948 call("remove_package_access", {
949 actor,
950 workspace,
951 ecosystem,
952 name,
953 user: "user" in who ? who.user : null,
954 team: "team" in who ? who.team : null,
955 surface: surface ?? null,
956 }),
957 setActionsAccess: (actor, workspace, ecosystem, name, repo, role, surface) =>
958 call("set_actions_access", { actor, workspace, ecosystem, name, repo, role, surface: surface ?? null }),
959 removeActionsAccess: (actor, workspace, ecosystem, name, repo, surface) =>
960 call("remove_actions_access", { actor, workspace, ecosystem, name, repo, surface: surface ?? null }),
961 storage: (workspace) => call("storage", { workspace }),
962 storageAll: () => call("storage_all", {}),
963 syncComposer: (repoId) => call("sync_composer", { repo_id: repoId }),
964 };
965}
966
967export function projectsClient(service: ServiceBinding): ProjectsApi {
968 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
969 return {
970 list: (workspace, viewer) => call("list", { workspace, viewer }),
971 get: (workspace, slug, viewer) => call("get", { workspace, slug, viewer }),
972 byRepo: (repoId) => call("by_repo", { repoId }),
973 describe: (actor, repoId, description) => call("describe", { actor, repoId, description }),
974 descriptions: (repoIds) => (repoIds.length ? call("descriptions", { repoIds }) : Promise.resolve({})),
975 create: (actor, workspace, input) => call("create", { actor, workspace, input }),
976 update: (actor, workspace, slug, changes) => call("update", { actor, workspace, slug, changes }),
977 setProductionImage: (actor, workspace, slug, change) => call("set_production_image", { actor, workspace, slug, change }),
978 externalProductions: () => call("external_productions", {}),
979 deploymentsChanged: (projectId, enabled) => call("deployments_changed", { projectId, enabled }),
980 shortcuts: (workspace, viewer) => call("shortcuts", { workspace, viewer }),
981 pin: (actor, workspace, slug, position) => call("pin", { actor, workspace, slug, position: position ?? null }),
982 unpin: (actor, workspace, slug) => call("unpin", { actor, workspace, slug }),
983 reorderPins: (actor, workspace, slugs) => call("reorder_pins", { actor, workspace, slugs }),
984 visited: (actor, projectId) => call("visited", { actor, projectId }),
985 publicLinks: (repos) => call("public_links", { repos }),
986 };
987}