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