Skip to content
960 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 { 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 createWorkspaceToken: (actor, slug, name, grant) =>
102 call("create_workspace_token", {
103 actor,
104 slug,
105 name,
106 scopes: grant?.scopes ?? null,
107 ttl_seconds: grant?.ttlSeconds ?? null,
108 admin: grant?.admin ?? false,
109 }),
110 removeWorkspaceToken: (actor, slug, id) =>
111 call("remove_workspace_token", { actor, slug, id }),
112 createFineGrainedToken: (user, input) =>
113 call("create_fine_grained_token", {
114 user,
115 name: input.name,
116 description: input.description ?? null,
117 ttl_seconds: input.ttlSeconds,
118 workspace: input.workspace,
119 repository_selection: input.repositorySelection,
120 repositories: input.repositories,
121 permissions: input.permissions,
122 }),
123 updateFineGrainedToken: (user, id, change) =>
124 call("update_fine_grained_token", {
125 user,
126 id,
127 name: change.name ?? null,
128 description: change.description ?? null,
129 repository_selection: change.repositorySelection ?? null,
130 repositories: change.repositories ?? null,
131 permissions: change.permissions ?? null,
132 }),
133 getTokenPolicy: (slug, viewer) => call("get_token_policy", { slug, viewer }),
134 setTokenPolicy: (actor, slug, change) =>
135 call("set_token_policy", {
136 actor,
137 slug,
138 allow_classic: change.allowClassic ?? null,
139 allow_fine_grained: change.allowFineGrained ?? null,
140 require_approval: change.requireApproval ?? null,
141 max_lifetime_days: change.maxLifetimeDays ?? null,
142 forbid_no_expiry: change.forbidNoExpiry ?? null,
143 surface: "web",
144 }),
145 listMemberTokens: (actor, slug, filter = {}) =>
146 call("list_member_tokens", { actor, slug, status: filter.status ?? null, kind: filter.kind ?? null }),
147 reviewTokenRequest: (actor, slug, id, approve, reason) =>
148 call("review_token_request", { actor, slug, id, approve, reason: reason ?? null, surface: "web" }),
149 revokeMemberToken: (actor, slug, id, reason) =>
150 call("revoke_member_token", { actor, slug, id, reason: reason ?? null, surface: "web" }),
151 userForSession: (sessionToken) => call("user_for_session", { sessionToken }),
152 registration: () => call("registration", {}),
153 listInvites: (user) => call("list_invites", { user }),
154 createInvite: (user, options = {}) =>
155 call("create_invite", { user, email: options.email ?? null, workspace: options.workspace ?? null, join: options.join ?? null, join_role: options.join ? (options.joinRole ?? null) : null }),
156 revokeInvite: (user, id) => call("revoke_invite", { user, id }),
157 checkInvite: (code, client, options = {}) =>
158 call("check_invite", {
159 code,
160 client: client ?? null,
161 viewer: options.viewer ?? null,
162 any_status: options.anyStatus ?? false,
163 email_proof: options.emailProof ?? null,
164 }),
165 acceptInvite: (user, code) => call("accept_invite", { user, code }),
166 inviteMember: (actor, slug, who) =>
167 call("invite_member", { actor, slug, email: who.email ?? "", username: who.username ?? null, role: who.role ?? null }),
168 listInvitations: (user) => call("list_invitations", { user }),
169 acceptInvitation: (user, id) => call("accept_invitation", { user, id, surface: "web" }),
170 declineInvitation: (user, id) => call("decline_invitation", { user, id, surface: "web" }),
171 findPeople: (query, limit) => call("find_people", { query, limit: limit ?? null }),
172 workspaceInvites: (slug, viewer) => call("workspace_invites", { slug, viewer }),
173 revokeWorkspaceInvite: (actor, slug, id) => call("revoke_workspace_invite", { actor, slug, id }),
174 requestAccess: (email, about, client) => call("request_access", { email, about, client: client ?? null }),
175 userForGitCredentials: (username, secret) =>
176 call("user_for_git_credentials", { username, secret }),
177 userForAccessToken: (token) => call("user_for_access_token", { token }),
178 userForSshKey: (fingerprint) => call("user_for_ssh_key", { fingerprint }),
179 userByUsername: (username) => call("user_by_username", { username }),
180 usernames: (ids) => call("usernames", { ids }),
181 usersForAudience: (ids) => call("users_for_audience", { ids }),
182 profile: (username) => call("profile", { username }),
183 updateProfile: (actor, fields) => call("update_profile", { actor, ...fields }),
184 profileWorkspaces: (username, viewer, publicIn) =>
185 call("profile_workspaces", { username, viewer, public: publicIn }),
186 listSshKeys: (user) => call("list_ssh_keys", { user }),
187 addSshKey: (user, title, publicKey) =>
188 call("add_ssh_key", { user, title, publicKey }),
189 removeSshKey: (user, id) => call("remove_ssh_key", { user, id }),
190 listAccessTokens: (user) => call("list_access_tokens", { user }),
191 createAccessToken: (user, name, ttlSeconds, grant) =>
192 call("create_access_token", {
193 user,
194 name,
195 ttlSeconds,
196 scopes: grant?.scopes ?? null,
197 listed: grant?.listed ?? false,
198 }),
199 updateAccessToken: (user, id, grant) =>
200 call("update_access_token", { user, id, scopes: grant.scopes }),
201 createAgentToken: (onBehalfOf, scope, ttlSeconds) =>
202 call("create_agent_token", { onBehalfOf, scope, ttlSeconds }),
203 removeAccessToken: (user, id) => call("remove_access_token", { user, id }),
204 createRunCredential: (input) => call("create_run_credential", input),
205 bindRunCredentials: (tokenHashes, runId) => call("bind_run_credentials", { tokenHashes, runId }),
206 revokeRunCredentials: (target) => call("revoke_run_credentials", target),
207 // Who has access to a repository; see access.ts.
208 repoAccess: (owner, name, viewer) => call("repo_access", { viewer, path: { namespace: owner, name } }),
209 addCollaborator: (actor, owner, name, invitee, role) =>
210 call("add_collaborator", { actor, path: { namespace: owner, name }, invitee, role }),
211 setCollaboratorRole: (actor, owner, name, username, role) =>
212 call("set_collaborator_role", { actor, path: { namespace: owner, name }, username, role }),
213 removeCollaborator: (actor, owner, name, username) =>
214 call("remove_collaborator", { actor, path: { namespace: owner, name }, username }),
215 collaboratorPermission: (viewer, owner, name, username) =>
216 call("collaborator_permission", { viewer, path: { namespace: owner, name }, username }),
217 myRepoInvitations: (user) => call("my_repo_invitations", { user }),
218 respondRepoInvitation: (user, id, accept) => call("respond_repo_invitation", { user, id, accept }),
219 revokeRepoInvitation: (actor, owner, name, id) =>
220 call("revoke_repo_invitation", { actor, path: { namespace: owner, name }, id }),
221 setBasePermission: (actor, slug, base) => call("set_base_permission", { actor, slug, base_permission: base }),
222 outsideCollaborators: (viewer, slug) => call("outside_collaborators", { viewer, slug }),
223 // A repository's deploy keys; see deploy-keys.ts.
224 listDeployKeys: (viewer, owner, name) => call("list_deploy_keys", { viewer, path: { namespace: owner, name } }),
225 addDeployKey: (actor, owner, name, key) =>
226 call("add_deploy_key", { actor, path: { namespace: owner, name }, title: key.title, key: key.key, read_only: key.readOnly }),
227 removeDeployKey: (actor, owner, name, id) => call("remove_deploy_key", { actor, path: { namespace: owner, name }, id }),
228 // Teams; see teams.ts.
229 listTeams: (viewer, workspace, query) => call("list_teams", { viewer, workspace, query: query ?? null }),
230 getTeam: (viewer, workspace, team) => call("get_team", { viewer, workspace, team }),
231 createTeam: (actor, workspace, team) => call("create_team", { actor, workspace, ...team }),
232 setTeamCreation: (actor, slug, setting) => call("set_team_creation", { actor, slug, team_creation: setting }),
233 updateTeam: (actor, workspace, team, changes) => call("update_team", { actor, workspace, team, ...changes }),
234 deleteTeam: (actor, workspace, team) => call("delete_team", { actor, workspace, team }),
235 teamMembers: (viewer, workspace, team, includeChildTeams) =>
236 call("team_members", { viewer, workspace, team, include_child_teams: includeChildTeams ?? false }),
237 setTeamMember: (actor, workspace, team, username, role) =>
238 call("set_team_member", { actor, workspace, team, username, role }),
239 removeTeamMember: (actor, workspace, team, username) =>
240 call("remove_team_member", { actor, workspace, team, username }),
241 childTeams: (viewer, workspace, team) => call("child_teams", { viewer, workspace, team }),
242 teamRepos: (viewer, workspace, team) => call("team_repos", { viewer, workspace, team }),
243 setTeamRepo: (actor, workspace, team, owner, name, role) =>
244 call("set_team_repo", { actor, workspace, team, repo: { namespace: owner, name }, role }),
245 removeTeamRepo: (actor, workspace, team, owner, name) =>
246 call("remove_team_repo", { actor, workspace, team, repo: { namespace: owner, name } }),
247 userTeams: (viewer, workspace, username) => call("user_teams", { viewer, workspace, username }),
248 teamMemberships: (viewer, workspace) => call("team_memberships", { viewer, workspace }),
249 };
250}
251
252/**
253 * The slug a renamed workspace has now, for a `workspace.renamed` handler:
254 * asked of identity by the workspace's id, so that renames delivered twice
255 * or out of order converge. Falls back to the event's `to`.
256 */
257export async function currentWorkspaceSlug(
258 identity: ServiceBinding,
259 renamed: { workspaceId: string; to: string },
260): Promise<string> {
261 const names = await identityClient(identity).usernames([renamed.workspaceId]);
262 return names[renamed.workspaceId] ?? renamed.to;
263}
264
265/** The slugs whose rows move to `current`: the two a rename names, less `current`. */
266export function staleSlugs(renamed: { from: string; to: string }, current: string): string[] {
267 return [...new Set([renamed.from, renamed.to])].filter((slug) => slug !== current);
268}
269
270/**
271 * Where a transferred repository is now, as `namespace/name`, for a
272 * `repo.transferred` handler: asked of repos by id, so transfers delivered
273 * twice or out of order converge. Falls back to the event's destination.
274 */
275export async function currentRepoPath(
276 repos: ServiceBinding,
277 transferred: { repoId: string; name: string; to: string },
278): Promise<string> {
279 const path = await rpc<{ namespace: string; name: string } | null>(repos, "path_by_id", { id: transferred.repoId });
280 return path ? `${path.namespace}/${path.name}` : `${transferred.to}/${transferred.name}`;
281}
282
283/** The paths whose rows move to `current`: the two a transfer names, less `current`. */
284export function stalePaths(transferred: { name: string; from: string; to: string }, current: string): string[] {
285 return [...new Set([transferred.from, transferred.to].map((ns) => `${ns}/${transferred.name}`))].filter(
286 (path) => path !== current,
287 );
288}
289
290/**
291 * A repository's path change, from `repo.transferred` or `repo.renamed`,
292 * read the same way: the two paths (`namespace/name`) the event names, old
293 * then new. Null for any other event.
294 */
295export type RepoMove = { repoId: string; paths: [string, string] };
296
297export function repoMove(event: { type: string; data: unknown }): RepoMove | null {
298 const data = event.data as Record<string, string>;
299 if (event.type === "repo.transferred") {
300 return { repoId: data.repoId!, paths: [`${data.from}/${data.name}`, `${data.to}/${data.name}`] };
301 }
302 if (event.type === "repo.renamed") {
303 return { repoId: data.repoId!, paths: [`${data.namespace}/${data.from}`, `${data.namespace}/${data.to}`] };
304 }
305 return null;
306}
307
308/**
309 * Where a moved repository is now, as `namespace/name`: asked of repos by
310 * id, so moves delivered twice or out of order converge. Falls back to the
311 * event's new path.
312 */
313export async function currentMovedPath(repos: ServiceBinding, move: RepoMove): Promise<string> {
314 const path = await rpc<{ namespace: string; name: string } | null>(repos, "path_by_id", { id: move.repoId });
315 return path ? `${path.namespace}/${path.name}` : move.paths[1];
316}
317
318/** The paths whose rows move to `current`: the two a move names, less `current`. */
319export function staleMovedPaths(move: RepoMove, current: string): string[] {
320 return [...new Set(move.paths)].filter((path) => path !== current);
321}
322
323/** Staff-only identity. Only sudo binds to it; see `IdentityAdminApi`. */
324export function identityAdminClient(service: ServiceBinding): IdentityAdminApi {
325 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
326 return {
327 workspaces: (query) => call("admin_workspaces", { query: query ?? null }),
328 workspace: (slug) => call("admin_workspace", { slug }),
329 waitlist: (query, status) => call("admin_waitlist", { query: query ?? null, status: status ?? null }),
330 waitlistPending: () => call("admin_waitlist_pending", {}),
331 decideWaitlist: (id, approve, staff, note) => call("admin_decide_waitlist", { id, approve, staff, note: note ?? null }),
332 invites: (query) => call("admin_invites", { query: query ?? null }),
333 revokeInvite: (id, staff) => call("admin_revoke_invite", { id, staff }),
334 mintInvite: (email, staff) => call("admin_mint_invite", { email, staff }),
335 grantInvites: (target, name, amount, note, staff) =>
336 call("admin_grant_invites", { target, name, amount, note, staff }),
337 inviteTree: (username) => call("admin_invite_tree", { username }),
338 workspaceInvites: (slug) => call("admin_workspace_invites", { slug }),
339 sharedInvites: () => call("admin_shared_invites", {}),
340 createSharedInvite: (link, staff) =>
341 call("admin_create_shared_invite", {
342 label: link.label,
343 max_uses: link.maxUses,
344 expires_on: link.expiresOn,
345 domains: link.domains,
346 staff,
347 }),
348 revokeSharedInvite: (id, staff) => call("admin_revoke_shared_invite", { id, staff }),
349 deletedWorkspaces: () => call("admin_deleted_workspaces", {}),
350 restoreWorkspace: (workspaceId, staff) => call("admin_restore_workspace", { workspaceId, staff }),
351 purgeWorkspace: (workspaceId, staff, confirm) => call("admin_purge_workspace", { workspaceId, staff, confirm }),
352 aliases: () => call("admin_aliases", {}),
353 setAlias: (alias, workspace, note, staff) => call("admin_set_alias", { alias, workspace, note, staff }),
354 removeAlias: (alias, reason, staff) => call("admin_remove_alias", { alias, reason, staff }),
355 };
356}
357
358export function reposClient(service: ServiceBinding): ReposApi {
359 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
360 return {
361 get: (path, viewer) => call("get", { path, viewer }),
362 getById: (id, viewer) => call("get_by_id", { id, viewer }),
363 readable: (ids, viewer) => call("readable", { ids, viewer }),
364 publicNamespaces: (ownerId) => call("public_namespaces", { ownerId }),
365 list: (viewer, options = {}) => call("list", { viewer, ...options }),
366 create: (owner, input) => call("create", { owner, ...input }),
367 update: (actor, path, changes) => call("update", { actor, path, ...changes }),
368 transfer: (actor, path, to) => call("transfer", { actor, path, to }),
369 delete: (actor, path, confirm) => call("delete", { actor, path, confirm }),
370 deleted: (viewer, namespace) => call("deleted", { viewer, namespace }),
371 restore: (actor, path) => call("restore", { actor, path }),
372 purge: (actor, path, confirm) => call("purge", { actor, path, confirm }),
373 rename: (actor, path, name) => call("rename", { actor, path, name }),
374 archive: (actor, path, archived) => call("archive", { actor, path, archived }),
375 setVisibility: (actor, path, isPrivate, confirm) => call("set_visibility", { actor, path, isPrivate, confirm }),
376 setDefaultBranch: (actor, path, branch) => call("set_default_branch", { actor, path, branch }),
377 renameBranch: (actor, path, from, to) => call("rename_branch", { actor, path, from, to }),
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 gitAccess: (path, viewer, service) =>
391 call("git_access", { path, viewer, service }),
392 branches: (path, viewer) => call("branches", { path, viewer }),
393 lastCommits: (path, viewer, ref, treePath) => call("last_commits", { path, viewer, ref, treePath }),
394 branchDrift: (path, viewer, base, heads) => call("branch_drift", { path, viewer, base, heads }),
395 tags: (path, viewer) => call("tags", { path, viewer }),
396 about: (path, viewer) => call("about", { path, viewer }),
397 languages: (path, viewer) => call("languages", { path, viewer }),
398 contributors: (path, viewer) => call("contributors", { path, viewer }),
399 license: (path, viewer) => call("license", { path, viewer }),
400 stars: (path, viewer) => call("stars", { path, viewer }),
401 star: (actor, path, starred) => call("star", { path, actor, starred }),
402 stargazers: (path, viewer, page) => call("stargazers", { path, viewer, page: page ?? null }),
403 starred: (username, viewer) => call("starred", { username, viewer }),
404 releases: (path, viewer) => call("releases", { path, viewer }),
405 release: (path, viewer, which) => call("release", { path, viewer, id: which.id ?? null, tag: which.tag ?? null, latest: which.latest ?? false }),
406 createRelease: (actor, path, release) => call("create_release", { path, actor, ...release }),
407 updateRelease: (actor, path, id, change) => call("update_release", { path, actor, id, ...change }),
408 deleteRelease: (actor, path, id) => call("delete_release", { path, actor, id }),
409 listFiles: (repoId, ref, limit) => call("list_files", { repoId, ref, skipDirs: [], limit }),
410 rawBlobs: (repoId, hashes, maxBytes) => call("raw_blobs", { repoId, hashes, maxBytes }),
411 rawFile: (repoId, ref, path, maxBytes) => call("raw_file", { repoId, ref, path, maxBytes }),
412 commitFile: (repo, actor, file) => call("commit_file", { repo, actor, ...file }),
413 land: (sourceId, actor, branch) => call("land", { sourceId, actor, branch }),
414 compare: (repoId, viewer, base, head, baseBranch) => call("compare", { repoId, viewer, base, head, baseBranch }),
415 claimBackups: (limit, maxRunning) => call("claim_backups", { limit, maxRunning }),
416 // The sandbox's own calls are snake_case (they come through the API).
417 failBackup: (jobId, token, error) => call("backup_fail", { job_id: jobId, token, error }),
418 };
419}
420
421/**
422 * `PullDetail`'s own fields that the work service writes in snake_case:
423 * `g1t_contracts::work::PullDetail` has no camelCase renaming, though what
424 * it holds (`Pull`, `CheckRun` and the rest) does. Each with its name here.
425 */
426const PULL_DETAIL_FIELDS = [
427 ["review_pending", "reviewPending"],
428 ["earlier_checks", "earlierChecks"],
429 ["required_checks", "requiredChecks"],
430 ["code_owners", "codeOwners"],
431] as const;
432
433/**
434 * A pull request's detail as the work service sent it, with its own fields
435 * in the camelCase this package uses: read at the edge, by `workClient`'s
436 * `getPull`. Either spelling is taken, so a service that already sends
437 * camelCase reads the same.
438 */
439export function pullDetailFromWire(raw: Record<string, unknown>): PullDetail {
440 const detail: Record<string, unknown> = { ...raw };
441 for (const [snake, camel] of PULL_DETAIL_FIELDS) {
442 if (snake in detail) {
443 if (!(camel in detail)) detail[camel] = detail[snake];
444 delete detail[snake];
445 }
446 }
447 if (typeof detail.reviewPending !== "boolean") detail.reviewPending = false;
448 return detail as PullDetail;
449}
450
451export function workClient(service: ServiceBinding): WorkApi {
452 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
453 return {
454 openIssue: (actor, repo, input) => call("open_issue", { actor, repo, ...input }),
455 delegateIssue: (actor, repo, input) => call("delegate_issue", { actor, repo, ...input }),
456 listIssues: (repo, viewer, filter = {}) => call("list_issues", { repo, viewer, ...filter }),
457 getIssue: (repo, number, viewer) => call("get_issue", { repo, number, viewer }),
458 updateIssue: (actor, repo, number, input) =>
459 call("update_issue", { actor, repo, number, ...input }),
460 closeIssue: (actor, repo, number, reason) =>
461 call("close_issue", { actor, repo, number, reason }),
462 reopenIssue: (actor, repo, number) => call("reopen_issue", { actor, repo, number }),
463 listLabels: (repo, viewer) => call("list_labels", { repo, viewer }),
464 saveLabel: (actor, repo, label) => call("save_label", { actor, repo, ...label }),
465 deleteLabel: (actor, repo, name) => call("delete_label", { actor, repo, name }),
466 addDefaultLabels: (actor, repo) => call("add_default_labels", { actor, repo }),
467 setLabels: (actor, repo, number, labels, change = "set") =>
468 call("set_labels", { actor, repo, number, labels, change }),
469 listMilestones: (repo, viewer, state) => call("list_milestones", { repo, viewer, state }),
470 getMilestone: (repo, number, viewer) => call("get_milestone", { repo, number, viewer }),
471 saveMilestone: (actor, repo, milestone) => call("save_milestone", { actor, repo, ...milestone }),
472 deleteMilestone: (actor, repo, number) => call("delete_milestone", { actor, repo, number }),
473 counts: (repo, viewer) => call("counts", { repo, viewer }),
474 addComment: (actor, repo, number, comment) =>
475 call("add_comment", { actor, repo, number, ...comment }),
476 editComment: (actor, repo, commentId, body) => call("edit_comment", { actor, repo, commentId, body }),
477 deleteComment: (actor, repo, commentId) => call("delete_comment", { actor, repo, commentId }),
478 startChecks: (pullId) => call("start_checks", { pullId }),
479 reportChecks: (runId, token, report) =>
480 call("report_checks", { runId, token, ...report }),
481 startReview: (pullId) => call("start_review", { pullId }),
482 failReview: (runId, token, error) => call("report_review", { runId, token, error }),
483 startMergecheck: (pullId) => call("start_mergecheck", { pullId }),
484 failMergecheck: (pullId, token, error) => call("report_mergecheck", { pullId, token, error }),
485 advance: (pullId) => call("advance", { pullId }),
486 stall: (pullId, reason) => call("stall", { pullId, reason }),
487 managedPulls: (repoId) => call("managed_pulls", { repoId }),
488 queue: (repo, viewer) => call("queue", { repo, viewer }),
489 queueBuild: (repoId) => call("queue_build", { repoId }),
490 failQueue: (entryId, token, error) => call("report_queue", { entryId, token, error }),
491 removeFromQueue: (actor, repo, number) => call("remove_from_queue", { actor, repo, number }),
492 messageAgent: (actor, repo, number, body) => call("message_agent", { actor, repo, number, body }),
493 catchUpJob: (pullId) => call("catch_up_job", { pullId }),
494 wakeForMessages: (pullId) => call("wake_for_messages", { pullId }),
495 getSettings: (repo, viewer) => call("get_settings", { repo, viewer }),
496 // Rulesets travel in snake_case (rules.ts).
497 listRulesets: (owner, viewer, includeParents = false) =>
498 call("list_rulesets", { viewer, ...owner, include_parents: includeParents }),
499 getRuleset: (owner, id, viewer) => call("get_ruleset", { viewer, ...owner, id }),
500 saveRuleset: (actor, owner, ruleset, id) => call("save_ruleset", { actor, ...owner, id: id ?? null, ruleset }),
501 deleteRuleset: (actor, owner, id) => call("delete_ruleset", { actor, ...owner, id }),
502 effectiveRules: (repo, name, viewer, target = "branch") => call("effective_rules", { viewer, repo, name, target }),
503 ruleEvaluations: (owner, viewer, filter = {}) => call("rule_evaluations", { viewer, ...owner, ...filter }),
504 seenChecks: (repo, viewer) => call("seen_checks", { repo, viewer }),
505 commitChecks: (repo, viewer, shas) => call("commit_checks", { repo, viewer, shas }),
506 getCheckRun: (repo, id, viewer) => call("get_check_run", { repo, id, viewer }),
507 checkRunAnnotations: (repo, id, viewer) => call("check_run_annotations", { repo, id, viewer }),
508 requestCheckAction: (actor, repo, id, identifier) => call("request_check_action", { actor, repo, id, identifier }),
509 rerequestCheckRun: (actor, repo, id) => call("rerequest_check_run", { actor, repo, id }),
510 codeownersErrors: (repo, viewer, ref) => call("codeowners_errors", { repo, viewer, ref: ref ?? null }),
511 updateSettings: (actor, repo, settings) =>
512 call("update_settings", { actor, repo, settings }),
513 openPull: (actor, repo, input) => call("open_pull", { actor, repo, ...input }),
514 listPulls: (repo, viewer, state, filter = {}) => call("list_pulls", { repo, viewer, state, ...filter }),
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) => call("catch_up_pull", { actor, repo, number }),
524 readyPull: (actor, repo, number, summary) =>
525 call("ready_pull", { actor, repo, number, summary }),
526 closePull: (actor, repo, number) => call("close_pull", { actor, repo, number }),
527 reopenPull: (actor, repo, number) => call("reopen_pull", { actor, repo, number }),
528 convertPullToDraft: (actor, repo, number) => call("convert_pull_to_draft", { actor, repo, number }),
529 mergePull: (actor, repo, number, options = {}) =>
530 call("merge_pull", { actor, repo, number, ...options }),
531 listActivePulls: (viewer) => call("list_active_pulls", { viewer }),
532 byAuthor: (username, viewer, filter = {}) => call("by_author", { username, viewer, ...filter }),
533 contributions: (username, viewer) => call("contributions", { username, viewer }),
534 startPlan: (actor, repo, brief) => call("start_plan", { actor, repo, brief }),
535 failPlan: (planId, token, error) => call("report_plan", { planId, token, error }),
536 getPlan: (repo, viewer, id) => call("get_plan", { repo, viewer, id }),
537 listPlans: (repo, viewer) => call("list_plans", { repo, viewer }),
538 applyPlan: (actor, repo, id, options = {}) =>
539 call("apply_plan", { actor, repo, id, ...options }),
540 queueIssue: (actor, repo, number, queued) =>
541 call("queue_issue", { actor, repo, number, queued }),
542 readyIssues: (repoId) => call("ready_issues", { repoId }),
543 listAssignedIssues: (viewer) => call("list_assigned_issues", { viewer }),
544 appendSession: (actor, repo, number, entries) =>
545 call("append_session", { actor, repo, number, entries }),
546 readSession: (repo, number, viewer, afterSeq = 0) =>
547 call("read_session", { repo, number, viewer, afterSeq }),
548 };
549}
550
551export function billingClient(service: ServiceBinding): BillingApi {
552 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
553 return {
554 status: () => call("status", {}),
555 account: (workspace, viewer) => call("account", { workspace, viewer }),
556 ledger: (workspace, viewer) => call("ledger", { workspace, viewer }),
557 credits: (workspace, viewer) => call("credits", { workspace, viewer }),
558 statement: (workspace, viewer, month = null, group = "day") => call("statement", { workspace, viewer, month, group }),
559 statementEntries: (workspace, viewer, filter) =>
560 call("statement_entries", {
561 workspace,
562 viewer,
563 month: filter.month,
564 kind: filter.kind,
565 day: filter.day ?? null,
566 project: filter.project ?? null,
567 before: filter.before ?? null,
568 }),
569 usage: (workspace, viewer, since) => call("usage", { workspace, viewer, since }),
570 tokenUsage: (workspace, viewer, options = {}) =>
571 call("token_usage", { workspace, viewer, person: options.person ?? null, days: options.days ?? null }),
572 recordTokens: (usage) => call("record_tokens", usage),
573 gatewayModels: () => call("gateway_models", {}),
574 modelDefaults: () => call("model_defaults", {}),
575 recordDiscovery: (provider, models, by, error = null) => call("record_discovery", { provider, models, by, error }),
576 gatewayAdmit: (workspace) => call("gateway_admit", { workspace }),
577 recordGateway: (record) => call("record_gateway", record),
578 gatewayRequests: (workspace, viewer, options = {}) =>
579 call("gateway_requests", { workspace, viewer, limit: options.limit ?? null, before: options.before ?? null }),
580 checkout: (actor, workspace, amountCents, returnUrl, method = "card") =>
581 call("checkout", { actor, workspace, amountCents, returnUrl, method }),
582 confirm: (workspace, viewer, session) => call("confirm", { workspace, viewer, session }),
583 canStart: (workspace) => call("can_start", { workspace }),
584 trial: (workspace, exempt) => call("trial", { workspace, exempt }),
585 startRun: (run) => call("start_run", run),
586 features: (workspace, viewer) => call("features", { workspace, viewer }),
587 subscribe: (actor, workspace, feature, returnUrl) =>
588 call("subscribe", { actor, workspace, feature, returnUrl }),
589 confirmSubscription: (workspace, viewer, session) =>
590 call("confirm_subscription", { workspace, viewer, session }),
591 cancelSubscription: (actor, workspace, feature, resume = false) =>
592 call("cancel_subscription", { actor, workspace, feature, resume }),
593 hasFeature: (workspace, feature) => call("has_feature", { workspace, feature }),
594 freeWorkspaces: (workspaces) => call("free_workspaces", { workspaces }),
595 chargeFeature: (charge) => call("charge_feature", charge),
596 billingPortal: (actor, workspace, returnUrl) => call("billing_portal", { actor, workspace, return_url: returnUrl }),
597 recordSandbox: (usage) => call("record_sandbox", usage),
598 limit: (workspace, viewer) => call("limit", { workspace, viewer }),
599 checkLimit: (workspace) => call("check_limit", { workspace }),
600 prices: () => call("prices", {}),
601 notePending: (workspace, source, costMicros, detail = null) => call("note_pending", { workspace, source, costMicros, detail }),
602 usageMeters: (workspace, viewer) => call("usage_meters", { workspace, viewer }),
603 setSpendLimit: (actor, workspace, spendLimitMicros, useFullLimit = false, raiseOnce = false) =>
604 call("set_spend_limit", { actor, workspace, spendLimitMicros, use_full_limit: useFullLimit, raise_once: raiseOnce }),
605 invoices: (workspace, viewer) => call("invoices", { workspace, viewer }),
606 entitlements: (workspace) => call("entitlements", { workspace }),
607 reserve: (reservation) => call("reserve", reservation),
608 settle: (reservationId, actualMicros) => call("settle", { reservationId, actualMicros }),
609 cardCheck: (actor, workspace, returnUrl) => call("card_check", { actor, workspace, returnUrl }),
610 confirmCardCheck: (workspace, viewer, session) => call("confirm_card_check", { workspace, viewer, session }),
611 requestLimit: (actor, workspace, request) => call("request_limit", { actor, workspace, ...request }),
612 limitRequests: (workspace, viewer) => call("limit_requests", { workspace, viewer }),
613 confirmSpike: (actor, workspace, keepGoing) => call("confirm_spike", { actor, workspace, keepGoing }),
614 setCaps: (actor, workspace, caps) => call("set_caps", { actor, workspace, ...caps }),
615 usageReport: (workspace, viewer, range) =>
616 call("usage_report", { workspace, viewer, from: range.from, until: range.until, products: range.products ?? [], projects: range.projects ?? [] }),
617 aiCredit: (workspace, viewer) => call("ai_credit", { workspace, viewer }),
618 buyAiCredit: (actor, workspace, amountCents, returnUrl) => call("buy_ai_credit", { actor, workspace, amountCents, returnUrl }),
619 confirmAiCredit: (workspace, viewer, session) => call("confirm_ai_credit", { workspace, viewer, session }),
620 setAiReload: (actor, workspace, reload) => call("set_ai_reload", { actor, workspace, ...reload }),
621 setBudget: (actor, workspace, budget) => call("set_budget", { actor, workspace, ...budget }),
622 billingDetails: (workspace, viewer) => call("billing_details", { workspace, viewer }),
623 setBillingDetails: (actor, workspace, details) => call("set_billing_details", { actor, workspace, ...details }),
624 };
625}
626
627export function billingAdminClient(service: ServiceBinding): BillingAdminApi {
628 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
629 return {
630 accounts: (query) => call("admin_accounts", { query: query ?? null }),
631 account: (id) => call("admin_account", { id }),
632 setTerms: (id, terms, by) => call("admin_set_terms", { id, terms, by }),
633 setAllowances: (id, allowances, note, by) => call("admin_set_allowances", { id, allowances, note, by }),
634 createEnterprise: (name, workspaces, by) => call("admin_create_enterprise", { name, workspaces, by }),
635 attach: (workspace, account, by) => call("admin_attach", { workspace, account, by }),
636 credit: (workspace, amountMicros, note, by, options = { kind: "goodwill" }) =>
637 call("admin_credit", {
638 workspace,
639 amount_micros: amountMicros,
640 note,
641 by,
642 kind: options.kind,
643 expires_at: options.expiresAt ?? null,
644 refund_for: options.refundFor ?? null,
645 refund_day: options.refundDay ?? null,
646 }),
647 credits: (filter = {}) =>
648 call("admin_credits", {
649 workspace: filter.workspace ?? null,
650 kind: filter.kind ?? null,
651 month: filter.month ?? null,
652 by: filter.by ?? null,
653 }),
654 revokeCredit: (id, note, by) => call("admin_revoke_credit", { id, note, by }),
655 resetBilling: (workspace, confirm, note, by) => call("admin_reset_billing", { workspace, confirm, note, by }),
656 billingLink: (workspace, by) => call("admin_billing_link", { workspace, by }),
657 stripe: (fix = false, by) => call("admin_stripe", { fix, by: by ?? null }),
658 enterpriseBilling: (id, email, by) => call("admin_enterprise_billing", { id, email, by }),
659 enterpriseAddress: (id, address, taxIdType, taxId, by) => call("admin_enterprise_address", { id, address, taxIdType, taxId, by }),
660 invoiceEnterprise: (id, by) => call("admin_invoice_enterprise", { id, by }),
661 accountsFor: (workspaces) => call("admin_accounts", { query: null, workspaces }),
662 signals: () => call("admin_signals", {}),
663 overview: () => call("admin_overview", {}),
664 sales: (workspace) => call("admin_sales", { workspace }),
665 setSales: (workspace, record, by) =>
666 call("admin_set_sales", {
667 workspace,
668 stage: record.stage,
669 owner: record.owner ?? null,
670 next_step: record.nextStep ?? null,
671 next_at: record.nextAt ?? null,
672 by,
673 }),
674 addNote: (workspace, text, by) => call("admin_add_note", { workspace, text, by }),
675 workspaceInvoices: (workspace) => call("admin_workspace_invoices", { workspace }),
676 allInvoices: (filter = {}) => call("admin_invoices", { status: filter.status ?? null, month: filter.month ?? null }),
677 audit: (filter = {}) =>
678 call("admin_audit", { by: filter.by ?? null, action: filter.action ?? null, before: filter.before ?? null }),
679 limitRequests: (status = "open") => call("admin_limit_requests", { status }),
680 decideLimitRequest: (id, decision, amountMicros, note, by) =>
681 call("admin_decide_limit_request", { id, decision, amount_micros: amountMicros, note, by }),
682 overages: () => call("admin_overages", {}),
683 goodwill: (workspace, amountMicros, reason, by, day = null) =>
684 call("admin_goodwill", { workspace, amount_micros: amountMicros, reason, by, day }),
685 velocity: () => call("admin_velocity", {}),
686 recordPayment: (workspace, amountMicros, reference, note, by) =>
687 call("admin_record_payment", { workspace, amount_micros: amountMicros, reference, note, by }),
688 costs: (days) => call("admin_costs", { days: days ?? null }),
689 costAlerts: () => call("admin_cost_alerts", {}),
690 spendCaps: () => call("admin_spend_caps", {}),
691 liftBreaker: (note, by) => call("admin_lift_breaker", { note, by }),
692 platformGuard: () => call("admin_platform_guard", {}),
693 setPause: (level, paused, note, by) => call("admin_set_pause", { level, paused, note, by }),
694 decideProposal: (id, decision, note, by) => call("admin_decide_proposal", { id, decision, note, by }),
695 setCostSettings: (settings, by) => call("admin_set_cost_settings", { settings, by }),
696 setCostMapping: (mapping, by) =>
697 call("admin_set_cost_mapping", {
698 product: mapping.product,
699 meter: mapping.meter,
700 bucket: mapping.bucket ?? "",
701 price_meter: mapping.priceMeter ?? null,
702 own_meter: mapping.ownMeter ?? null,
703 scale_to_own: mapping.scaleToOwn ?? false,
704 drift_percent: mapping.driftPercent ?? null,
705 note: mapping.note ?? "",
706 remove: mapping.remove ?? false,
707 by,
708 }),
709 runCosts: (by) => call("admin_run_costs", { by }),
710 models: () => call("admin_models", {}),
711 decideModel: (model, decision, details, reason, by) =>
712 call("admin_decide_model", {
713 model,
714 decision,
715 name: details.name ?? null,
716 tier_hint: details.tierHint ?? null,
717 prices: details.prices
718 ? {
719 input_micros: details.prices.inputMicros,
720 output_micros: details.prices.outputMicros,
721 cache_read_micros: details.prices.cacheReadMicros,
722 cache_write_micros: details.prices.cacheWriteMicros,
723 cache_write_1h_micros: details.prices.cacheWrite1hMicros,
724 threshold: details.prices.threshold,
725 over_input_micros: details.prices.overInputMicros,
726 over_output_micros: details.prices.overOutputMicros,
727 over_cache_read_micros: details.prices.overCacheReadMicros,
728 over_cache_write_micros: details.prices.overCacheWriteMicros,
729 over_cache_write_1h_micros: details.prices.overCacheWrite1hMicros,
730 }
731 : null,
732 reason,
733 by,
734 }),
735 setModelDefault: (purpose, value, reason, by) =>
736 call("admin_set_model_default", {
737 purpose,
738 model: value.model ?? null,
739 tier: value.tier ?? null,
740 effort: value.effort ?? null,
741 reason,
742 by,
743 }),
744 };
745}
746
747export function eventsClient(service: ServiceBinding): EventsApi {
748 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
749 return {
750 publish: (events) => call("publish", { events }),
751 list: (query) => call("list", query),
752 };
753}
754
755export function integrationsClient(service: ServiceBinding): IntegrationsApi {
756 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
757 return {
758 list: (workspace, viewer) => call("list", { workspace, viewer }),
759 connect: (actor, workspace, input) => call("connect", { actor, workspace, ...input }),
760 update: (actor, workspace, id, input) => call("update", { actor, workspace, id, ...input }),
761 disconnect: (actor, workspace, id) => call("disconnect", { actor, workspace, id }),
762 test: (actor, workspace, id) => call("test", { actor, workspace, id }),
763 deliveries: (workspace, viewer, id) => call("deliveries", { workspace, viewer, id }),
764 resolve: (workspace, viewer, reference) => call("resolve", { workspace, viewer, reference }),
765 references: (workspace, text, limit) => call("references", { workspace, text, limit }),
766 import: (actor, repo, reference, assign) => call("import", { actor, repo, reference, assign }),
767 links: (repo, number) => call("links", { repo, number }),
768 modelProvider: (workspace) => call("model_provider", { workspace }),
769 openModelSession: (run) => call("open_model_session", run),
770 modelUpstream: (token) => call("model_upstream", { token }),
771 gatewayUpstream: (workspace) => call("gateway_upstream", { workspace }),
772 gatewayProviders: (workspace) => call("gateway_providers", { workspace }),
773 closeModelSessions: (tokenHashes) => call("close_model_sessions", { token_hashes: tokenHashes }),
774 capModelSessions: (tokenHashes, capMicros) => call("cap_model_sessions", { token_hashes: tokenHashes, cap_micros: capMicros }),
775 routes: (workspace, viewer) => call("routes", { workspace, viewer }),
776 setRoutes: (actor, workspace, routes) => call("set_routes", { actor, workspace, routes }),
777 };
778}
779
780export function webhooksClient(service: ServiceBinding): WebhooksApi {
781 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
782 return {
783 list: (viewer, owner) => call("list", { viewer, ...owner }),
784 create: (actor, owner, input) => call("create", { actor, ...owner, ...input }),
785 update: (actor, owner, id, input) => call("update", { actor, ...owner, id, ...input }),
786 delete: (actor, owner, id) => call("delete", { actor, ...owner, id }),
787 ping: (actor, owner, id) => call("ping", { actor, ...owner, id }),
788 deliveries: (viewer, owner, id) => call("deliveries", { viewer, ...owner, id }),
789 redeliver: (actor, owner, deliveryId) => call("redeliver", { actor, ...owner, deliveryId }),
790 };
791}
792
793export function actionsClient(service: ServiceBinding): ActionsApi {
794 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
795 return {
796 workflows: (repo, viewer) => call("workflows", { repo, viewer }),
797 runs: (repo, viewer, filter = {}) => call("runs", { repo, viewer, ...filter }),
798 run: (repo, viewer, id, attempt) => call("run", { repo, viewer, id, attempt: attempt ?? null }),
799 logs: (repo, viewer, job, after = 0) => call("logs", { repo, viewer, job, after }),
800 summaries: (repo, viewer, id, attempt) => call("summaries", { repo, viewer, id, attempt: attempt ?? null }),
801 jobLogText: (repo, viewer, job) => call("job_log_text", { repo, viewer, job }),
802 runLogs: (repo, viewer, id, attempt) => call("run_logs", { repo, viewer, id, attempt: attempt ?? null }),
803 dispatch: (actor, repo, workflow, ref, inputs) => call("dispatch", { actor, repo, workflow, ref, inputs }),
804 cancel: (actor, repo, id, force = false) => call("cancel", { actor, repo, id, force }),
805 rerun: (actor, repo, id, failedOnly = false, options = {}) =>
806 call("rerun", { actor, repo, id, failed_only: failedOnly, job: options.job ?? null, debug: options.debug ?? false }),
807 setWorkflowEnabled: (actor, repo, workflow, enabled) =>
808 call("set_workflow_enabled", { actor, repo, workflow, enabled }),
809 settings: (actor, owner, kind) => call("settings", { actor, ...owner, kind }),
810 setSetting: (actor, owner, kind, name, value, options = {}) =>
811 call("set_setting", { actor, ...owner, kind, name, value, ...options }),
812 deleteSetting: (actor, owner, kind, name, id) => call("delete_setting", { actor, ...owner, kind, name, id }),
813 approveRun: (actor, repo, id) => call("approve_run", { actor, repo, id }),
814 pendingDeployments: (repo, viewer, id) => call("pending_deployments", { repo, viewer, id }),
815 reviewDeployments: (actor, repo, id, state, environments = [], comment) =>
816 call("review_deployments", { actor, repo, id, state, environments, comment: comment ?? null }),
817 actionsSettings: (repo, viewer) => call("actions_settings", { repo, viewer }),
818 setActionsSettings: (actor, repo, change) => call("set_actions_settings", { actor, repo, ...change }),
819 workspaceActionsSettings: (workspace, viewer) => call("workspace_actions_settings", { workspace, viewer }),
820 setWorkspaceActionsSettings: (actor, workspace, change) =>
821 call("set_workspace_actions_settings", { actor, workspace, ...change }),
822 environments: (repo, viewer) => call("environments", { repo, viewer }),
823 setEnvironment: (actor, repo, name, change) => call("set_environment", { actor, repo, name, ...change }),
824 deleteEnvironment: (actor, repo, name) => call("delete_environment", { actor, repo, name }),
825 artifacts: (repo, viewer, filter = {}) => call("artifacts", { repo, viewer, ...filter }),
826 artifactDownload: (repo, viewer, by) => call("artifact_download", { repo, viewer, ...by }),
827 deleteArtifact: (actor, repo, id) => call("delete_artifact", { actor, repo, id }),
828 artifactRetention: (repo, viewer, days) => call("artifact_retention", { repo, viewer, days }),
829 };
830}
831
832
833/** Self-hosted runners, kept by the actions service. */
834export function runnersClient(service: ServiceBinding): RunnersApi {
835 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
836 return {
837 stuck: (viewer) => call("stuck_jobs", { viewer }),
838 list: (actor, owner) => call("runners", { actor, ...owner }),
839 createToken: (actor, owner, group) => call("create_registration_token", { actor, ...owner, group }),
840 remove: (actor, owner, id) => call("remove_runner", { actor, ...owner, id }),
841 groups: (actor, workspace) => call("runner_groups", { actor, workspace }),
842 setGroup: (actor, workspace, group) => call("set_runner_group", { actor, workspace, ...group }),
843 deleteGroup: (actor, workspace, id) => call("delete_runner_group", { actor, workspace, id }),
844 settings: (actor, owner) => call("runner_settings", { actor, ...owner }),
845 setSettings: (actor, owner, change) => call("set_runner_settings", { actor, ...owner, ...change }),
846 };
847}
848
849export function deploymentsClient(service: ServiceBinding): DeploymentsApi {
850 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
851 return {
852 settings: (project, viewer) => call("settings", { project, viewer }),
853 updateSettings: (actor, project, changes) => call("update_settings", { actor, project, changes }),
854 list: (project, viewer) => call("list", { project, viewer }),
855 get: (project, id, viewer) => call("get", { project, id, viewer }),
856 redeploy: (actor, project, branch) => call("redeploy", { actor, project, branch }),
857 takeDown: (actor, project, branch) => call("take_down", { actor, project, branch }),
858 stack: (actor, project, branch) => call("stack", { actor, project, branch }),
859 overview: (workspace, viewer) => call("overview", { workspace, viewer }),
860 usage: (workspace, viewer) => call("usage", { workspace, viewer }),
861 domains: (project, viewer) => call("domains", { project, viewer }),
862 addDomain: (actor, project, hostname, options = {}) =>
863 call("add_domain", { actor, project, hostname, twin: !!options.twin }),
864 removeDomain: (actor, project, id) => call("remove_domain", { actor, project, id }),
865 refreshDomain: (actor, project, id) => call("refresh_domain", { actor, project, id }),
866 repoDeployments: (repo, viewer, filter = {}) => call("list_deployments", { repo, viewer, ...filter }),
867 repoDeployment: (repo, id, viewer) => call("get_deployment", { repo, id, viewer }),
868 environments: (repo, viewer) => call("list_environments", { repo, viewer }),
869 createDeployment: (actor, repo, input) => call("create_deployment", { repo, actor, ...input }),
870 createDeploymentStatus: (actor, repo, id, input) => call("create_deployment_status", { repo, actor, id, ...input }),
871 };
872}
873
874/** Packages: the registries beside the code (services/packages). */
875export function packagesClient(service: ServiceBinding): PackagesApi {
876 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
877 return {
878 list: (workspace, viewer, filter = {}) =>
879 call("list_packages", {
880 workspace,
881 viewer,
882 ecosystem: filter.ecosystem ?? null,
883 repo_id: filter.repoId ?? null,
884 query: filter.query ?? null,
885 }),
886 get: (workspace, ecosystem, name, viewer) => call("get_package", { workspace, ecosystem, name, viewer }),
887 deleteVersion: (actor, workspace, ecosystem, name, version, surface) =>
888 call("delete_version", { actor, workspace, ecosystem, name, version, surface: surface ?? null }),
889 deletePackage: (actor, workspace, ecosystem, name, surface) =>
890 call("delete_package", { actor, workspace, ecosystem, name, surface: surface ?? null }),
891 set: (actor, workspace, ecosystem, name, change, surface) =>
892 call("set_package", {
893 actor,
894 workspace,
895 ecosystem,
896 name,
897 visibility: change.visibility ?? null,
898 link: change.link ?? null,
899 unlink: change.unlink ?? false,
900 inherit_access: change.inheritAccess ?? null,
901 surface: surface ?? null,
902 }),
903 settings: (workspace, ecosystem, name, viewer) => call("package_settings", { workspace, ecosystem, name, viewer }),
904 deleted: (workspace, viewer) => call("deleted_packages", { workspace, viewer }),
905 restorePackage: (actor, workspace, ecosystem, name, surface) =>
906 call("restore_package", { actor, workspace, ecosystem, name, surface: surface ?? null }),
907 restoreVersion: (actor, workspace, ecosystem, name, version, surface) =>
908 call("restore_version", { actor, workspace, ecosystem, name, version, surface: surface ?? null }),
909 setAccess: (actor, workspace, ecosystem, name, who, role, surface) =>
910 call("set_package_access", {
911 actor,
912 workspace,
913 ecosystem,
914 name,
915 user: "user" in who ? who.user : null,
916 team: "team" in who ? who.team : null,
917 role,
918 surface: surface ?? null,
919 }),
920 removeAccess: (actor, workspace, ecosystem, name, who, surface) =>
921 call("remove_package_access", {
922 actor,
923 workspace,
924 ecosystem,
925 name,
926 user: "user" in who ? who.user : null,
927 team: "team" in who ? who.team : null,
928 surface: surface ?? null,
929 }),
930 setActionsAccess: (actor, workspace, ecosystem, name, repo, role, surface) =>
931 call("set_actions_access", { actor, workspace, ecosystem, name, repo, role, surface: surface ?? null }),
932 removeActionsAccess: (actor, workspace, ecosystem, name, repo, surface) =>
933 call("remove_actions_access", { actor, workspace, ecosystem, name, repo, surface: surface ?? null }),
934 storage: (workspace) => call("storage", { workspace }),
935 storageAll: () => call("storage_all", {}),
936 syncComposer: (repoId) => call("sync_composer", { repo_id: repoId }),
937 };
938}
939
940export function projectsClient(service: ServiceBinding): ProjectsApi {
941 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
942 return {
943 list: (workspace, viewer) => call("list", { workspace, viewer }),
944 get: (workspace, slug, viewer) => call("get", { workspace, slug, viewer }),
945 byRepo: (repoId) => call("by_repo", { repoId }),
946 create: (actor, workspace, input) => call("create", { actor, workspace, input }),
947 update: (actor, workspace, slug, changes) => call("update", { actor, workspace, slug, changes }),
948 deploymentsChanged: (projectId, enabled) => call("deployments_changed", { projectId, enabled }),
949 dependencies: (workspace, slug, viewer) => call("dependencies", { workspace, slug, viewer }),
950 addDependency: (actor, workspace, slug, on, as) => call("add_dependency", { actor, workspace, slug, on, as }),
951 removeDependency: (actor, workspace, slug, on) => call("remove_dependency", { actor, workspace, slug, on }),
952 graph: (projectId) => call("graph", { projectId }),
953 shortcuts: (workspace, viewer) => call("shortcuts", { workspace, viewer }),
954 pin: (actor, workspace, slug, position) => call("pin", { actor, workspace, slug, position: position ?? null }),
955 unpin: (actor, workspace, slug) => call("unpin", { actor, workspace, slug }),
956 reorderPins: (actor, workspace, slugs) => call("reorder_pins", { actor, workspace, slugs }),
957 visited: (actor, projectId) => call("visited", { actor, projectId }),
958 publicLinks: (repos) => call("public_links", { repos }),
959 };
960}