Skip to content

g1t/packages/contracts/src/clients.ts

785 lines47,727 bytesCodeBlame
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) =>
45 call("register", { username, email, password, invite_code: inviteCode ?? null, client: client ?? null }),
46 signIn: (username, password, client) => call("sign_in", { username, password, client: client ?? null }),
47 signOut: (sessionToken) => call("sign_out", { sessionToken }),
48 resendVerification: (user) => call("resend_verification", { user }),
49 verifyEmail: (token) => call("verify_email", { token }),
50 requestPasswordReset: (email, client) => call("request_password_reset", { email, client: client ?? null }),
51 resetPassword: (token, password) =>
52 call("reset_password", { token, password }),
53 deviceStart: (clientName) => call("device_start", { clientName }),
54 deviceLookup: (userCode) => call("device_lookup", { userCode }),
55 deviceResolve: (userCode, user, approve) =>
56 call("device_resolve", { userCode, user, approve }),
57 deviceClaim: (deviceCode) => call("device_claim", { deviceCode }),
58 oauthAuthorize: (user, approval) => call("oauth_authorize", { user, ...approval }),
59 oauthExchange: (code, codeVerifier, clientId, redirectUri) =>
60 call("oauth_exchange", { code, codeVerifier, clientId, redirectUri }),
61 oauthRefresh: (refreshToken, clientId) =>
62 call("oauth_refresh", { refreshToken, clientId }),
63 listOAuthGrants: (user) => call("list_oauth_grants", { user }),
64 revokeOAuthGrant: (user, id) => call("revoke_oauth_grant", { user, id }),
65 updateOAuthGrant: (user, id, grant) =>
66 call("update_oauth_grant", { user, id, scopes: grant.scopes }),
67 createWorkspace: (user, slug, name) => call("create_workspace", { user, slug, name }),
68 getWorkspace: (slug) => call("get_workspace", { slug }),
69 workspaceResidency: (slug) => call("workspace_residency", { slug }),
70 setWorkspaceResidency: (actor, slug, residency) => call("set_workspace_residency", { actor, slug, residency }),
71 listMembers: (slug, viewer) => call("list_members", { slug, viewer }),
72 addMember: (actor, slug, username) => call("add_member", { actor, slug, username }),
73 removeMember: (actor, slug, username) =>
74 call("remove_member", { actor, slug, username }),
75 updateWorkspace: (actor, slug, details) =>
76 call("update_workspace", { actor, slug, ...details }),
77 renameWorkspace: (actor, slug, newSlug) => call("rename_workspace", { actor, slug, newSlug }),
78 checkWorkspaceRename: (actor, slug, newSlug) =>
79 call("check_workspace_rename", { actor, slug, newSlug }),
80 resolveSlug: (slug) => call("resolve_slug", { slug }),
81 deleteWorkspace: (actor, slug, confirm) => call("delete_workspace", { actor, slug, confirm }),
82 checkWorkspaceDeletion: (actor, slug) => call("check_workspace_deletion", { actor, slug }),
83 setWorkspaceAvatar: (actor, slug, image) => call("set_workspace_avatar", { actor, slug, image }),
84 setUserAvatar: (user, image) => call("set_user_avatar", { user, image }),
85 listWorkspaceTokens: (slug, viewer) => call("list_workspace_tokens", { slug, viewer }),
86 createWorkspaceToken: (actor, slug, name, grant) =>
87 call("create_workspace_token", {
88 actor,
89 slug,
90 name,
91 scopes: grant?.scopes ?? null,
92 ttl_seconds: grant?.ttlSeconds ?? null,
93 }),
94 removeWorkspaceToken: (actor, slug, id) =>
95 call("remove_workspace_token", { actor, slug, id }),
96 userForSession: (sessionToken) => call("user_for_session", { sessionToken }),
97 registration: () => call("registration", {}),
98 listInvites: (user) => call("list_invites", { user }),
99 createInvite: (user, options = {}) =>
100 call("create_invite", { user, email: options.email ?? null, workspace: options.workspace ?? null }),
101 revokeInvite: (user, id) => call("revoke_invite", { user, id }),
102 checkInvite: (code, client, options = {}) =>
103 call("check_invite", {
104 code,
105 client: client ?? null,
106 viewer: options.viewer ?? null,
107 any_status: options.anyStatus ?? false,
108 }),
109 acceptInvite: (user, code) => call("accept_invite", { user, code }),
110 inviteMember: (actor, slug, email) => call("invite_member", { actor, slug, email }),
111 workspaceInvites: (slug, viewer) => call("workspace_invites", { slug, viewer }),
112 revokeWorkspaceInvite: (actor, slug, id) => call("revoke_workspace_invite", { actor, slug, id }),
113 requestAccess: (email, about, client) => call("request_access", { email, about, client: client ?? null }),
114 userForGitCredentials: (username, secret) =>
115 call("user_for_git_credentials", { username, secret }),
116 userForAccessToken: (token) => call("user_for_access_token", { token }),
117 userForSshKey: (fingerprint) => call("user_for_ssh_key", { fingerprint }),
118 userByUsername: (username) => call("user_by_username", { username }),
119 usernames: (ids) => call("usernames", { ids }),
120 profile: (username) => call("profile", { username }),
121 updateProfile: (actor, fields) => call("update_profile", { actor, ...fields }),
122 profileWorkspaces: (username, viewer, publicIn) =>
123 call("profile_workspaces", { username, viewer, public: publicIn }),
124 listSshKeys: (user) => call("list_ssh_keys", { user }),
125 addSshKey: (user, title, publicKey) =>
126 call("add_ssh_key", { user, title, publicKey }),
127 removeSshKey: (user, id) => call("remove_ssh_key", { user, id }),
128 listAccessTokens: (user) => call("list_access_tokens", { user }),
129 createAccessToken: (user, name, ttlSeconds, grant) =>
130 call("create_access_token", {
131 user,
132 name,
133 ttlSeconds,
134 scopes: grant?.scopes ?? null,
135 listed: grant?.listed ?? false,
136 }),
137 updateAccessToken: (user, id, grant) =>
138 call("update_access_token", { user, id, scopes: grant.scopes }),
139 createAgentToken: (onBehalfOf, scope, ttlSeconds) =>
140 call("create_agent_token", { onBehalfOf, scope, ttlSeconds }),
141 removeAccessToken: (user, id) => call("remove_access_token", { user, id }),
142 createRunCredential: (input) => call("create_run_credential", input),
143 bindRunCredentials: (tokenHashes, runId) => call("bind_run_credentials", { tokenHashes, runId }),
144 revokeRunCredentials: (target) => call("revoke_run_credentials", target),
145 // Who has access to a repository; see access.ts.
146 repoAccess: (owner, name, viewer) => call("repo_access", { viewer, path: { namespace: owner, name } }),
147 addCollaborator: (actor, owner, name, invitee, role) =>
148 call("add_collaborator", { actor, path: { namespace: owner, name }, invitee, role }),
149 setCollaboratorRole: (actor, owner, name, username, role) =>
150 call("set_collaborator_role", { actor, path: { namespace: owner, name }, username, role }),
151 removeCollaborator: (actor, owner, name, username) =>
152 call("remove_collaborator", { actor, path: { namespace: owner, name }, username }),
153 collaboratorPermission: (viewer, owner, name, username) =>
154 call("collaborator_permission", { viewer, path: { namespace: owner, name }, username }),
155 myRepoInvitations: (user) => call("my_repo_invitations", { user }),
156 respondRepoInvitation: (user, id, accept) => call("respond_repo_invitation", { user, id, accept }),
157 revokeRepoInvitation: (actor, owner, name, id) =>
158 call("revoke_repo_invitation", { actor, path: { namespace: owner, name }, id }),
159 setBasePermission: (actor, slug, base) => call("set_base_permission", { actor, slug, base_permission: base }),
160 outsideCollaborators: (viewer, slug) => call("outside_collaborators", { viewer, slug }),
161 // Teams; see teams.ts.
162 listTeams: (viewer, workspace, query) => call("list_teams", { viewer, workspace, query: query ?? null }),
163 getTeam: (viewer, workspace, team) => call("get_team", { viewer, workspace, team }),
164 createTeam: (actor, workspace, team) => call("create_team", { actor, workspace, ...team }),
165 setTeamCreation: (actor, slug, setting) => call("set_team_creation", { actor, slug, team_creation: setting }),
166 updateTeam: (actor, workspace, team, changes) => call("update_team", { actor, workspace, team, ...changes }),
167 deleteTeam: (actor, workspace, team) => call("delete_team", { actor, workspace, team }),
168 teamMembers: (viewer, workspace, team, includeChildTeams) =>
169 call("team_members", { viewer, workspace, team, include_child_teams: includeChildTeams ?? false }),
170 setTeamMember: (actor, workspace, team, username, role) =>
171 call("set_team_member", { actor, workspace, team, username, role }),
172 removeTeamMember: (actor, workspace, team, username) =>
173 call("remove_team_member", { actor, workspace, team, username }),
174 childTeams: (viewer, workspace, team) => call("child_teams", { viewer, workspace, team }),
175 teamRepos: (viewer, workspace, team) => call("team_repos", { viewer, workspace, team }),
176 setTeamRepo: (actor, workspace, team, owner, name, role) =>
177 call("set_team_repo", { actor, workspace, team, repo: { namespace: owner, name }, role }),
178 removeTeamRepo: (actor, workspace, team, owner, name) =>
179 call("remove_team_repo", { actor, workspace, team, repo: { namespace: owner, name } }),
180 userTeams: (viewer, workspace, username) => call("user_teams", { viewer, workspace, username }),
181 teamMemberships: (viewer, workspace) => call("team_memberships", { viewer, workspace }),
182 };
183}
184
185/**
186 * The slug a renamed workspace has now, for a `workspace.renamed` handler:
187 * asked of identity by the workspace's id, so that renames delivered twice
188 * or out of order converge. Falls back to the event's `to`.
189 */
190export async function currentWorkspaceSlug(
191 identity: ServiceBinding,
192 renamed: { workspaceId: string; to: string },
193): Promise<string> {
194 const names = await identityClient(identity).usernames([renamed.workspaceId]);
195 return names[renamed.workspaceId] ?? renamed.to;
196}
197
198/** The slugs whose rows move to `current`: the two a rename names, less `current`. */
199export function staleSlugs(renamed: { from: string; to: string }, current: string): string[] {
200 return [...new Set([renamed.from, renamed.to])].filter((slug) => slug !== current);
201}
202
203/**
204 * Where a transferred repository is now, as `namespace/name`, for a
205 * `repo.transferred` handler: asked of repos by id, so transfers delivered
206 * twice or out of order converge. Falls back to the event's destination.
207 */
208export async function currentRepoPath(
209 repos: ServiceBinding,
210 transferred: { repoId: string; name: string; to: string },
211): Promise<string> {
212 const path = await rpc<{ namespace: string; name: string } | null>(repos, "path_by_id", { id: transferred.repoId });
213 return path ? `${path.namespace}/${path.name}` : `${transferred.to}/${transferred.name}`;
214}
215
216/** The paths whose rows move to `current`: the two a transfer names, less `current`. */
217export function stalePaths(transferred: { name: string; from: string; to: string }, current: string): string[] {
218 return [...new Set([transferred.from, transferred.to].map((ns) => `${ns}/${transferred.name}`))].filter(
219 (path) => path !== current,
220 );
221}
222
223/**
224 * A repository's path change, from `repo.transferred` or `repo.renamed`,
225 * read the same way: the two paths (`namespace/name`) the event names, old
226 * then new. Null for any other event.
227 */
228export type RepoMove = { repoId: string; paths: [string, string] };
229
230export function repoMove(event: { type: string; data: unknown }): RepoMove | null {
231 const data = event.data as Record<string, string>;
232 if (event.type === "repo.transferred") {
233 return { repoId: data.repoId!, paths: [`${data.from}/${data.name}`, `${data.to}/${data.name}`] };
234 }
235 if (event.type === "repo.renamed") {
236 return { repoId: data.repoId!, paths: [`${data.namespace}/${data.from}`, `${data.namespace}/${data.to}`] };
237 }
238 return null;
239}
240
241/**
242 * Where a moved repository is now, as `namespace/name`: asked of repos by
243 * id, so moves delivered twice or out of order converge. Falls back to the
244 * event's new path.
245 */
246export async function currentMovedPath(repos: ServiceBinding, move: RepoMove): Promise<string> {
247 const path = await rpc<{ namespace: string; name: string } | null>(repos, "path_by_id", { id: move.repoId });
248 return path ? `${path.namespace}/${path.name}` : move.paths[1];
249}
250
251/** The paths whose rows move to `current`: the two a move names, less `current`. */
252export function staleMovedPaths(move: RepoMove, current: string): string[] {
253 return [...new Set(move.paths)].filter((path) => path !== current);
254}
255
256/** Staff-only identity. Only sudo binds to it; see `IdentityAdminApi`. */
257export function identityAdminClient(service: ServiceBinding): IdentityAdminApi {
258 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
259 return {
260 workspaces: (query) => call("admin_workspaces", { query: query ?? null }),
261 workspace: (slug) => call("admin_workspace", { slug }),
262 waitlist: (query, status) => call("admin_waitlist", { query: query ?? null, status: status ?? null }),
263 waitlistPending: () => call("admin_waitlist_pending", {}),
264 decideWaitlist: (id, approve, staff, note) => call("admin_decide_waitlist", { id, approve, staff, note: note ?? null }),
265 invites: (query) => call("admin_invites", { query: query ?? null }),
266 revokeInvite: (id, staff) => call("admin_revoke_invite", { id, staff }),
267 mintInvite: (email, staff) => call("admin_mint_invite", { email, staff }),
268 grantInvites: (target, name, amount, note, staff) =>
269 call("admin_grant_invites", { target, name, amount, note, staff }),
270 inviteTree: (username) => call("admin_invite_tree", { username }),
271 workspaceInvites: (slug) => call("admin_workspace_invites", { slug }),
272 deletedWorkspaces: () => call("admin_deleted_workspaces", {}),
273 restoreWorkspace: (workspaceId, staff) => call("admin_restore_workspace", { workspaceId, staff }),
274 purgeWorkspace: (workspaceId, staff, confirm) => call("admin_purge_workspace", { workspaceId, staff, confirm }),
275 aliases: () => call("admin_aliases", {}),
276 setAlias: (alias, workspace, note, staff) => call("admin_set_alias", { alias, workspace, note, staff }),
277 removeAlias: (alias, reason, staff) => call("admin_remove_alias", { alias, reason, staff }),
278 };
279}
280
281export function reposClient(service: ServiceBinding): ReposApi {
282 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
283 return {
284 get: (path, viewer) => call("get", { path, viewer }),
285 getById: (id, viewer) => call("get_by_id", { id, viewer }),
286 readable: (ids, viewer) => call("readable", { ids, viewer }),
287 publicNamespaces: (ownerId) => call("public_namespaces", { ownerId }),
288 list: (viewer, options = {}) => call("list", { viewer, ...options }),
289 create: (owner, input) => call("create", { owner, ...input }),
290 update: (actor, path, changes) => call("update", { actor, path, ...changes }),
291 transfer: (actor, path, to) => call("transfer", { actor, path, to }),
292 delete: (actor, path, confirm) => call("delete", { actor, path, confirm }),
293 deleted: (viewer, namespace) => call("deleted", { viewer, namespace }),
294 restore: (actor, path) => call("restore", { actor, path }),
295 purge: (actor, path, confirm) => call("purge", { actor, path, confirm }),
296 rename: (actor, path, name) => call("rename", { actor, path, name }),
297 archive: (actor, path, archived) => call("archive", { actor, path, archived }),
298 setVisibility: (actor, path, isPrivate, confirm) => call("set_visibility", { actor, path, isPrivate, confirm }),
299 setDefaultBranch: (actor, path, branch) => call("set_default_branch", { actor, path, branch }),
300 renameBranch: (actor, path, from, to) => call("rename_branch", { actor, path, from, to }),
301 resolveBranch: (repoId, branch) => call("resolve_branch", { repoId, branch }),
302 statusById: (id) => call("status_by_id", { id }),
303 storageOptions: () => call("storage_options", {}),
304 resolvePath: (path) => call("resolve_path", { path }),
305 tree: (path, viewer, ref, treePath) =>
306 call("tree", { path, viewer, ref, treePath }),
307 blob: (path, viewer, ref, filePath) =>
308 call("blob", { path, viewer, ref, filePath }),
309 log: (path, viewer, ref, limit) => call("log", { path, viewer, ref, limit }),
310 blame: (path, viewer, ref, filePath) => call("blame", { path, viewer, ref, filePath }),
311 forkForPull: (sourceId, pullId, actor) =>
312 call("fork_for_pull", { sourceId, pullId, actor }),
313 gitAccess: (path, viewer, service) =>
314 call("git_access", { path, viewer, service }),
315 branches: (path, viewer) => call("branches", { path, viewer }),
316 lastCommits: (path, viewer, ref, treePath) => call("last_commits", { path, viewer, ref, treePath }),
317 tags: (path, viewer) => call("tags", { path, viewer }),
318 about: (path, viewer) => call("about", { path, viewer }),
319 languages: (path, viewer) => call("languages", { path, viewer }),
320 contributors: (path, viewer) => call("contributors", { path, viewer }),
321 license: (path, viewer) => call("license", { path, viewer }),
322 stars: (path, viewer) => call("stars", { path, viewer }),
323 star: (actor, path, starred) => call("star", { path, actor, starred }),
324 stargazers: (path, viewer, page) => call("stargazers", { path, viewer, page: page ?? null }),
325 starred: (username, viewer) => call("starred", { username, viewer }),
326 releases: (path, viewer) => call("releases", { path, viewer }),
327 release: (path, viewer, which) => call("release", { path, viewer, id: which.id ?? null, tag: which.tag ?? null, latest: which.latest ?? false }),
328 createRelease: (actor, path, release) => call("create_release", { path, actor, ...release }),
329 updateRelease: (actor, path, id, change) => call("update_release", { path, actor, id, ...change }),
330 deleteRelease: (actor, path, id) => call("delete_release", { path, actor, id }),
331 listFiles: (repoId, ref, limit) => call("list_files", { repoId, ref, skipDirs: [], limit }),
332 rawBlobs: (repoId, hashes, maxBytes) => call("raw_blobs", { repoId, hashes, maxBytes }),
333 commitFile: (repo, actor, file) => call("commit_file", { repo, actor, ...file }),
334 land: (sourceId, actor, branch) => call("land", { sourceId, actor, branch }),
335 compare: (repoId, viewer, base, head, baseBranch) => call("compare", { repoId, viewer, base, head, baseBranch }),
336 claimBackups: (limit, maxRunning) => call("claim_backups", { limit, maxRunning }),
337 // The sandbox's own calls are snake_case (they come through the API).
338 failBackup: (jobId, token, error) => call("backup_fail", { job_id: jobId, token, error }),
339 };
340}
341
342/**
343 * `PullDetail`'s own fields that the work service writes in snake_case:
344 * `g1t_contracts::work::PullDetail` has no camelCase renaming, though what
345 * it holds (`Pull`, `CheckRun` and the rest) does. Each with its name here.
346 */
347const PULL_DETAIL_FIELDS = [
348 ["review_pending", "reviewPending"],
349 ["earlier_checks", "earlierChecks"],
350 ["required_checks", "requiredChecks"],
351 ["code_owners", "codeOwners"],
352] as const;
353
354/**
355 * A pull request's detail as the work service sent it, with its own fields
356 * in the camelCase this package uses: read at the edge, by `workClient`'s
357 * `getPull`. Either spelling is taken, so a service that already sends
358 * camelCase reads the same.
359 */
360export function pullDetailFromWire(raw: Record<string, unknown>): PullDetail {
361 const detail: Record<string, unknown> = { ...raw };
362 for (const [snake, camel] of PULL_DETAIL_FIELDS) {
363 if (snake in detail) {
364 if (!(camel in detail)) detail[camel] = detail[snake];
365 delete detail[snake];
366 }
367 }
368 if (typeof detail.reviewPending !== "boolean") detail.reviewPending = false;
369 return detail as PullDetail;
370}
371
372export function workClient(service: ServiceBinding): WorkApi {
373 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
374 return {
375 openIssue: (actor, repo, input) => call("open_issue", { actor, repo, ...input }),
376 delegateIssue: (actor, repo, input) => call("delegate_issue", { actor, repo, ...input }),
377 listIssues: (repo, viewer, filter = {}) => call("list_issues", { repo, viewer, ...filter }),
378 getIssue: (repo, number, viewer) => call("get_issue", { repo, number, viewer }),
379 updateIssue: (actor, repo, number, input) =>
380 call("update_issue", { actor, repo, number, ...input }),
381 closeIssue: (actor, repo, number, reason) =>
382 call("close_issue", { actor, repo, number, reason }),
383 reopenIssue: (actor, repo, number) => call("reopen_issue", { actor, repo, number }),
384 listLabels: (repo, viewer) => call("list_labels", { repo, viewer }),
385 saveLabel: (actor, repo, label) => call("save_label", { actor, repo, ...label }),
386 deleteLabel: (actor, repo, name) => call("delete_label", { actor, repo, name }),
387 addDefaultLabels: (actor, repo) => call("add_default_labels", { actor, repo }),
388 setLabels: (actor, repo, number, labels, change = "set") =>
389 call("set_labels", { actor, repo, number, labels, change }),
390 listMilestones: (repo, viewer, state) => call("list_milestones", { repo, viewer, state }),
391 getMilestone: (repo, number, viewer) => call("get_milestone", { repo, number, viewer }),
392 saveMilestone: (actor, repo, milestone) => call("save_milestone", { actor, repo, ...milestone }),
393 deleteMilestone: (actor, repo, number) => call("delete_milestone", { actor, repo, number }),
394 counts: (repo, viewer) => call("counts", { repo, viewer }),
395 addComment: (actor, repo, number, comment) =>
396 call("add_comment", { actor, repo, number, ...comment }),
397 startChecks: (pullId) => call("start_checks", { pullId }),
398 reportChecks: (runId, token, report) =>
399 call("report_checks", { runId, token, ...report }),
400 startReview: (pullId) => call("start_review", { pullId }),
401 failReview: (runId, token, error) => call("report_review", { runId, token, error }),
402 startMergecheck: (pullId) => call("start_mergecheck", { pullId }),
403 failMergecheck: (pullId, token, error) => call("report_mergecheck", { pullId, token, error }),
404 advance: (pullId) => call("advance", { pullId }),
405 stall: (pullId, reason) => call("stall", { pullId, reason }),
406 managedPulls: (repoId) => call("managed_pulls", { repoId }),
407 queue: (repo, viewer) => call("queue", { repo, viewer }),
408 queueBuild: (repoId) => call("queue_build", { repoId }),
409 failQueue: (entryId, token, error) => call("report_queue", { entryId, token, error }),
410 removeFromQueue: (actor, repo, number) => call("remove_from_queue", { actor, repo, number }),
411 messageAgent: (actor, repo, number, body) => call("message_agent", { actor, repo, number, body }),
412 catchUpJob: (pullId) => call("catch_up_job", { pullId }),
413 wakeForMessages: (pullId) => call("wake_for_messages", { pullId }),
414 getSettings: (repo, viewer) => call("get_settings", { repo, viewer }),
415 // Rulesets travel in snake_case (rules.ts).
416 listRulesets: (owner, viewer, includeParents = false) =>
417 call("list_rulesets", { viewer, ...owner, include_parents: includeParents }),
418 getRuleset: (owner, id, viewer) => call("get_ruleset", { viewer, ...owner, id }),
419 saveRuleset: (actor, owner, ruleset, id) => call("save_ruleset", { actor, ...owner, id: id ?? null, ruleset }),
420 deleteRuleset: (actor, owner, id) => call("delete_ruleset", { actor, ...owner, id }),
421 effectiveRules: (repo, name, viewer, target = "branch") => call("effective_rules", { viewer, repo, name, target }),
422 ruleEvaluations: (owner, viewer, filter = {}) => call("rule_evaluations", { viewer, ...owner, ...filter }),
423 seenChecks: (repo, viewer) => call("seen_checks", { repo, viewer }),
424 commitChecks: (repo, viewer, shas) => call("commit_checks", { repo, viewer, shas }),
425 getCheckRun: (repo, id, viewer) => call("get_check_run", { repo, id, viewer }),
426 checkRunAnnotations: (repo, id, viewer) => call("check_run_annotations", { repo, id, viewer }),
427 requestCheckAction: (actor, repo, id, identifier) => call("request_check_action", { actor, repo, id, identifier }),
428 rerequestCheckRun: (actor, repo, id) => call("rerequest_check_run", { actor, repo, id }),
429 codeownersErrors: (repo, viewer, ref) => call("codeowners_errors", { repo, viewer, ref: ref ?? null }),
430 updateSettings: (actor, repo, settings) =>
431 call("update_settings", { actor, repo, settings }),
432 openPull: (actor, repo, input) => call("open_pull", { actor, repo, ...input }),
433 listPulls: (repo, viewer, state, filter = {}) => call("list_pulls", { repo, viewer, state, ...filter }),
434 pullsForRepos: (repoIds, viewer, limit) => call("pulls_for_repos", { repoIds, viewer, limit }),
435 // Its own fields arrive in snake_case: read into camelCase here.
436 getPull: (repo, number, viewer) =>
437 call<Result<Record<string, unknown>>>("get_pull", { repo, number, viewer }).then(
438 (found): Result<PullDetail> => (found.ok ? { ok: true, value: pullDetailFromWire(found.value) } : found),
439 ),
440 updatePull: (actor, repo, number, changes) =>
441 call("update_pull", { actor, repo, number, ...changes }),
442 catchUpPull: (actor, repo, number) => call("catch_up_pull", { actor, repo, number }),
443 readyPull: (actor, repo, number, summary) =>
444 call("ready_pull", { actor, repo, number, summary }),
445 closePull: (actor, repo, number) => call("close_pull", { actor, repo, number }),
446 mergePull: (actor, repo, number, options = {}) =>
447 call("merge_pull", { actor, repo, number, ...options }),
448 listActivePulls: (viewer) => call("list_active_pulls", { viewer }),
449 byAuthor: (username, viewer, filter = {}) => call("by_author", { username, viewer, ...filter }),
450 startPlan: (actor, repo, brief) => call("start_plan", { actor, repo, brief }),
451 failPlan: (planId, token, error) => call("report_plan", { planId, token, error }),
452 getPlan: (repo, viewer, id) => call("get_plan", { repo, viewer, id }),
453 listPlans: (repo, viewer) => call("list_plans", { repo, viewer }),
454 applyPlan: (actor, repo, id, options = {}) =>
455 call("apply_plan", { actor, repo, id, ...options }),
456 queueIssue: (actor, repo, number, queued) =>
457 call("queue_issue", { actor, repo, number, queued }),
458 readyIssues: (repoId) => call("ready_issues", { repoId }),
459 listAssignedIssues: (viewer) => call("list_assigned_issues", { viewer }),
460 appendSession: (actor, repo, number, entries) =>
461 call("append_session", { actor, repo, number, entries }),
462 readSession: (repo, number, viewer, afterSeq = 0) =>
463 call("read_session", { repo, number, viewer, afterSeq }),
464 };
465}
466
467export function billingClient(service: ServiceBinding): BillingApi {
468 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
469 return {
470 status: () => call("status", {}),
471 account: (workspace, viewer) => call("account", { workspace, viewer }),
472 ledger: (workspace, viewer) => call("ledger", { workspace, viewer }),
473 credits: (workspace, viewer) => call("credits", { workspace, viewer }),
474 statement: (workspace, viewer, month = null, group = "day") => call("statement", { workspace, viewer, month, group }),
475 statementEntries: (workspace, viewer, filter) =>
476 call("statement_entries", {
477 workspace,
478 viewer,
479 month: filter.month,
480 kind: filter.kind,
481 day: filter.day ?? null,
482 project: filter.project ?? null,
483 before: filter.before ?? null,
484 }),
485 usage: (workspace, viewer, since) => call("usage", { workspace, viewer, since }),
486 tokenUsage: (workspace, viewer, options = {}) =>
487 call("token_usage", { workspace, viewer, person: options.person ?? null, days: options.days ?? null }),
488 recordTokens: (usage) => call("record_tokens", usage),
489 gatewayModels: () => call("gateway_models", {}),
490 gatewayAdmit: (workspace) => call("gateway_admit", { workspace }),
491 recordGateway: (record) => call("record_gateway", record),
492 gatewayRequests: (workspace, viewer, options = {}) =>
493 call("gateway_requests", { workspace, viewer, limit: options.limit ?? null, before: options.before ?? null }),
494 checkout: (actor, workspace, amountCents, returnUrl, method = "card") =>
495 call("checkout", { actor, workspace, amountCents, returnUrl, method }),
496 confirm: (workspace, viewer, session) => call("confirm", { workspace, viewer, session }),
497 canStart: (workspace) => call("can_start", { workspace }),
498 trial: (workspace, exempt) => call("trial", { workspace, exempt }),
499 startRun: (run) => call("start_run", run),
500 features: (workspace, viewer) => call("features", { workspace, viewer }),
501 subscribe: (actor, workspace, feature, returnUrl) =>
502 call("subscribe", { actor, workspace, feature, returnUrl }),
503 confirmSubscription: (workspace, viewer, session) =>
504 call("confirm_subscription", { workspace, viewer, session }),
505 cancelSubscription: (actor, workspace, feature, resume = false) =>
506 call("cancel_subscription", { actor, workspace, feature, resume }),
507 hasFeature: (workspace, feature) => call("has_feature", { workspace, feature }),
508 freeWorkspaces: (workspaces) => call("free_workspaces", { workspaces }),
509 chargeFeature: (charge) => call("charge_feature", charge),
510 billingPortal: (actor, workspace, returnUrl) => call("billing_portal", { actor, workspace, return_url: returnUrl }),
511 recordSandbox: (usage) => call("record_sandbox", usage),
512 limit: (workspace, viewer) => call("limit", { workspace, viewer }),
513 checkLimit: (workspace) => call("check_limit", { workspace }),
514 prices: () => call("prices", {}),
515 notePending: (workspace, source, costMicros, detail = null) => call("note_pending", { workspace, source, costMicros, detail }),
516 usageMeters: (workspace, viewer) => call("usage_meters", { workspace, viewer }),
517 setSpendLimit: (actor, workspace, spendLimitMicros, useFullLimit = false, raiseOnce = false) =>
518 call("set_spend_limit", { actor, workspace, spendLimitMicros, use_full_limit: useFullLimit, raise_once: raiseOnce }),
519 invoices: (workspace, viewer) => call("invoices", { workspace, viewer }),
520 entitlements: (workspace) => call("entitlements", { workspace }),
521 reserve: (reservation) => call("reserve", reservation),
522 settle: (reservationId, actualMicros) => call("settle", { reservationId, actualMicros }),
523 cardCheck: (actor, workspace, returnUrl) => call("card_check", { actor, workspace, returnUrl }),
524 confirmCardCheck: (workspace, viewer, session) => call("confirm_card_check", { workspace, viewer, session }),
525 requestLimit: (actor, workspace, request) => call("request_limit", { actor, workspace, ...request }),
526 limitRequests: (workspace, viewer) => call("limit_requests", { workspace, viewer }),
527 confirmSpike: (actor, workspace, keepGoing) => call("confirm_spike", { actor, workspace, keepGoing }),
528 setCaps: (actor, workspace, caps) => call("set_caps", { actor, workspace, ...caps }),
529 usageReport: (workspace, viewer, range) =>
530 call("usage_report", { workspace, viewer, from: range.from, until: range.until, products: range.products ?? [], projects: range.projects ?? [] }),
531 aiCredit: (workspace, viewer) => call("ai_credit", { workspace, viewer }),
532 buyAiCredit: (actor, workspace, amountCents, returnUrl) => call("buy_ai_credit", { actor, workspace, amountCents, returnUrl }),
533 confirmAiCredit: (workspace, viewer, session) => call("confirm_ai_credit", { workspace, viewer, session }),
534 setAiReload: (actor, workspace, reload) => call("set_ai_reload", { actor, workspace, ...reload }),
535 setBudget: (actor, workspace, budget) => call("set_budget", { actor, workspace, ...budget }),
536 billingDetails: (workspace, viewer) => call("billing_details", { workspace, viewer }),
537 setBillingDetails: (actor, workspace, details) => call("set_billing_details", { actor, workspace, ...details }),
538 };
539}
540
541export function billingAdminClient(service: ServiceBinding): BillingAdminApi {
542 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
543 return {
544 accounts: (query) => call("admin_accounts", { query: query ?? null }),
545 account: (id) => call("admin_account", { id }),
546 setTerms: (id, terms, by) => call("admin_set_terms", { id, terms, by }),
547 setAllowances: (id, allowances, note, by) => call("admin_set_allowances", { id, allowances, note, by }),
548 createEnterprise: (name, workspaces, by) => call("admin_create_enterprise", { name, workspaces, by }),
549 attach: (workspace, account, by) => call("admin_attach", { workspace, account, by }),
550 credit: (workspace, amountMicros, note, by, options = { kind: "goodwill" }) =>
551 call("admin_credit", {
552 workspace,
553 amount_micros: amountMicros,
554 note,
555 by,
556 kind: options.kind,
557 expires_at: options.expiresAt ?? null,
558 refund_for: options.refundFor ?? null,
559 refund_day: options.refundDay ?? null,
560 }),
561 credits: (filter = {}) =>
562 call("admin_credits", {
563 workspace: filter.workspace ?? null,
564 kind: filter.kind ?? null,
565 month: filter.month ?? null,
566 by: filter.by ?? null,
567 }),
568 revokeCredit: (id, note, by) => call("admin_revoke_credit", { id, note, by }),
569 resetBilling: (workspace, confirm, note, by) => call("admin_reset_billing", { workspace, confirm, note, by }),
570 billingLink: (workspace, by) => call("admin_billing_link", { workspace, by }),
571 stripe: (fix = false, by) => call("admin_stripe", { fix, by: by ?? null }),
572 enterpriseBilling: (id, email, by) => call("admin_enterprise_billing", { id, email, by }),
573 enterpriseAddress: (id, address, taxIdType, taxId, by) => call("admin_enterprise_address", { id, address, taxIdType, taxId, by }),
574 invoiceEnterprise: (id, by) => call("admin_invoice_enterprise", { id, by }),
575 accountsFor: (workspaces) => call("admin_accounts", { query: null, workspaces }),
576 signals: () => call("admin_signals", {}),
577 overview: () => call("admin_overview", {}),
578 sales: (workspace) => call("admin_sales", { workspace }),
579 setSales: (workspace, record, by) =>
580 call("admin_set_sales", {
581 workspace,
582 stage: record.stage,
583 owner: record.owner ?? null,
584 next_step: record.nextStep ?? null,
585 next_at: record.nextAt ?? null,
586 by,
587 }),
588 addNote: (workspace, text, by) => call("admin_add_note", { workspace, text, by }),
589 workspaceInvoices: (workspace) => call("admin_workspace_invoices", { workspace }),
590 allInvoices: (filter = {}) => call("admin_invoices", { status: filter.status ?? null, month: filter.month ?? null }),
591 audit: (filter = {}) =>
592 call("admin_audit", { by: filter.by ?? null, action: filter.action ?? null, before: filter.before ?? null }),
593 limitRequests: (status = "open") => call("admin_limit_requests", { status }),
594 decideLimitRequest: (id, decision, amountMicros, note, by) =>
595 call("admin_decide_limit_request", { id, decision, amount_micros: amountMicros, note, by }),
596 overages: () => call("admin_overages", {}),
597 goodwill: (workspace, amountMicros, reason, by, day = null) =>
598 call("admin_goodwill", { workspace, amount_micros: amountMicros, reason, by, day }),
599 velocity: () => call("admin_velocity", {}),
600 recordPayment: (workspace, amountMicros, reference, note, by) =>
601 call("admin_record_payment", { workspace, amount_micros: amountMicros, reference, note, by }),
602 costs: (days) => call("admin_costs", { days: days ?? null }),
603 costAlerts: () => call("admin_cost_alerts", {}),
604 spendCaps: () => call("admin_spend_caps", {}),
605 liftBreaker: (note, by) => call("admin_lift_breaker", { note, by }),
606 decideProposal: (id, decision, note, by) => call("admin_decide_proposal", { id, decision, note, by }),
607 setCostSettings: (settings, by) => call("admin_set_cost_settings", { settings, by }),
608 setCostMapping: (mapping, by) =>
609 call("admin_set_cost_mapping", {
610 product: mapping.product,
611 meter: mapping.meter,
612 bucket: mapping.bucket ?? "",
613 price_meter: mapping.priceMeter ?? null,
614 own_meter: mapping.ownMeter ?? null,
615 scale_to_own: mapping.scaleToOwn ?? false,
616 drift_percent: mapping.driftPercent ?? null,
617 note: mapping.note ?? "",
618 remove: mapping.remove ?? false,
619 by,
620 }),
621 runCosts: (by) => call("admin_run_costs", { by }),
622 };
623}
624
625export function eventsClient(service: ServiceBinding): EventsApi {
626 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
627 return {
628 publish: (events) => call("publish", { events }),
629 list: (query) => call("list", query),
630 };
631}
632
633export function integrationsClient(service: ServiceBinding): IntegrationsApi {
634 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
635 return {
636 list: (workspace, viewer) => call("list", { workspace, viewer }),
637 connect: (actor, workspace, input) => call("connect", { actor, workspace, ...input }),
638 update: (actor, workspace, id, input) => call("update", { actor, workspace, id, ...input }),
639 disconnect: (actor, workspace, id) => call("disconnect", { actor, workspace, id }),
640 test: (actor, workspace, id) => call("test", { actor, workspace, id }),
641 deliveries: (workspace, viewer, id) => call("deliveries", { workspace, viewer, id }),
642 resolve: (workspace, viewer, reference) => call("resolve", { workspace, viewer, reference }),
643 references: (workspace, text, limit) => call("references", { workspace, text, limit }),
644 import: (actor, repo, reference, assign) => call("import", { actor, repo, reference, assign }),
645 links: (repo, number) => call("links", { repo, number }),
646 modelProvider: (workspace) => call("model_provider", { workspace }),
647 openModelSession: (run) => call("open_model_session", run),
648 modelUpstream: (token) => call("model_upstream", { token }),
649 gatewayUpstream: (workspace) => call("gateway_upstream", { workspace }),
650 gatewayProviders: (workspace) => call("gateway_providers", { workspace }),
651 closeModelSessions: (tokenHashes) => call("close_model_sessions", { token_hashes: tokenHashes }),
652 routes: (workspace, viewer) => call("routes", { workspace, viewer }),
653 setRoutes: (actor, workspace, routes) => call("set_routes", { actor, workspace, routes }),
654 };
655}
656
657export function webhooksClient(service: ServiceBinding): WebhooksApi {
658 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
659 return {
660 list: (viewer, owner) => call("list", { viewer, ...owner }),
661 create: (actor, owner, input) => call("create", { actor, ...owner, ...input }),
662 update: (actor, owner, id, input) => call("update", { actor, ...owner, id, ...input }),
663 delete: (actor, owner, id) => call("delete", { actor, ...owner, id }),
664 ping: (actor, owner, id) => call("ping", { actor, ...owner, id }),
665 deliveries: (viewer, owner, id) => call("deliveries", { viewer, ...owner, id }),
666 redeliver: (actor, owner, deliveryId) => call("redeliver", { actor, ...owner, deliveryId }),
667 };
668}
669
670export function actionsClient(service: ServiceBinding): ActionsApi {
671 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
672 return {
673 workflows: (repo, viewer) => call("workflows", { repo, viewer }),
674 runs: (repo, viewer, filter = {}) => call("runs", { repo, viewer, ...filter }),
675 run: (repo, viewer, id) => call("run", { repo, viewer, id }),
676 logs: (repo, viewer, job, after = 0) => call("logs", { repo, viewer, job, after }),
677 dispatch: (actor, repo, workflow, ref, inputs) => call("dispatch", { actor, repo, workflow, ref, inputs }),
678 cancel: (actor, repo, id) => call("cancel", { actor, repo, id }),
679 rerun: (actor, repo, id, failedOnly = false) => call("rerun", { actor, repo, id, failed_only: failedOnly }),
680 setWorkflowEnabled: (actor, repo, workflow, enabled) =>
681 call("set_workflow_enabled", { actor, repo, workflow, enabled }),
682 settings: (actor, owner, kind) => call("settings", { actor, ...owner, kind }),
683 setSetting: (actor, owner, kind, name, value, options = {}) =>
684 call("set_setting", { actor, ...owner, kind, name, value, ...options }),
685 deleteSetting: (actor, owner, kind, name, id) => call("delete_setting", { actor, ...owner, kind, name, id }),
686 };
687}
688
689
690/** Self-hosted runners, kept by the actions service. */
691export function runnersClient(service: ServiceBinding): RunnersApi {
692 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
693 return {
694 stuck: (viewer) => call("stuck_jobs", { viewer }),
695 list: (actor, owner) => call("runners", { actor, ...owner }),
696 createToken: (actor, owner, group) => call("create_registration_token", { actor, ...owner, group }),
697 remove: (actor, owner, id) => call("remove_runner", { actor, ...owner, id }),
698 groups: (actor, workspace) => call("runner_groups", { actor, workspace }),
699 setGroup: (actor, workspace, group) => call("set_runner_group", { actor, workspace, ...group }),
700 deleteGroup: (actor, workspace, id) => call("delete_runner_group", { actor, workspace, id }),
701 settings: (actor, owner) => call("runner_settings", { actor, ...owner }),
702 setSettings: (actor, owner, change) => call("set_runner_settings", { actor, ...owner, ...change }),
703 };
704}
705
706export function deploymentsClient(service: ServiceBinding): DeploymentsApi {
707 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
708 return {
709 settings: (project, viewer) => call("settings", { project, viewer }),
710 updateSettings: (actor, project, changes) => call("update_settings", { actor, project, changes }),
711 list: (project, viewer) => call("list", { project, viewer }),
712 get: (project, id, viewer) => call("get", { project, id, viewer }),
713 redeploy: (actor, project, branch) => call("redeploy", { actor, project, branch }),
714 takeDown: (actor, project, branch) => call("take_down", { actor, project, branch }),
715 stack: (actor, project, branch) => call("stack", { actor, project, branch }),
716 overview: (workspace, viewer) => call("overview", { workspace, viewer }),
717 usage: (workspace, viewer) => call("usage", { workspace, viewer }),
718 domains: (project, viewer) => call("domains", { project, viewer }),
719 addDomain: (actor, project, hostname, options = {}) =>
720 call("add_domain", { actor, project, hostname, twin: !!options.twin }),
721 removeDomain: (actor, project, id) => call("remove_domain", { actor, project, id }),
722 refreshDomain: (actor, project, id) => call("refresh_domain", { actor, project, id }),
723 repoDeployments: (repo, viewer, filter = {}) => call("list_deployments", { repo, viewer, ...filter }),
724 repoDeployment: (repo, id, viewer) => call("get_deployment", { repo, id, viewer }),
725 environments: (repo, viewer) => call("list_environments", { repo, viewer }),
726 createDeployment: (actor, repo, input) => call("create_deployment", { repo, actor, ...input }),
727 createDeploymentStatus: (actor, repo, id, input) => call("create_deployment_status", { repo, actor, id, ...input }),
728 };
729}
730
731/** Packages: the registries beside the code (services/packages). */
732export function packagesClient(service: ServiceBinding): PackagesApi {
733 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
734 return {
735 list: (workspace, viewer, filter = {}) =>
736 call("list_packages", {
737 workspace,
738 viewer,
739 ecosystem: filter.ecosystem ?? null,
740 repo_id: filter.repoId ?? null,
741 query: filter.query ?? null,
742 }),
743 get: (workspace, ecosystem, name, viewer) => call("get_package", { workspace, ecosystem, name, viewer }),
744 deleteVersion: (actor, workspace, ecosystem, name, version, surface) =>
745 call("delete_version", { actor, workspace, ecosystem, name, version, surface: surface ?? null }),
746 deletePackage: (actor, workspace, ecosystem, name, surface) =>
747 call("delete_package", { actor, workspace, ecosystem, name, surface: surface ?? null }),
748 set: (actor, workspace, ecosystem, name, change, surface) =>
749 call("set_package", {
750 actor,
751 workspace,
752 ecosystem,
753 name,
754 visibility: change.visibility ?? null,
755 link: change.link ?? null,
756 unlink: change.unlink ?? false,
757 surface: surface ?? null,
758 }),
759 storage: (workspace) => call("storage", { workspace }),
760 storageAll: () => call("storage_all", {}),
761 syncComposer: (repoId) => call("sync_composer", { repo_id: repoId }),
762 };
763}
764
765export function projectsClient(service: ServiceBinding): ProjectsApi {
766 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
767 return {
768 list: (workspace, viewer) => call("list", { workspace, viewer }),
769 get: (workspace, slug, viewer) => call("get", { workspace, slug, viewer }),
770 byRepo: (repoId) => call("by_repo", { repoId }),
771 create: (actor, workspace, input) => call("create", { actor, workspace, input }),
772 update: (actor, workspace, slug, changes) => call("update", { actor, workspace, slug, changes }),
773 deploymentsChanged: (projectId, enabled) => call("deployments_changed", { projectId, enabled }),
774 dependencies: (workspace, slug, viewer) => call("dependencies", { workspace, slug, viewer }),
775 addDependency: (actor, workspace, slug, on, as) => call("add_dependency", { actor, workspace, slug, on, as }),
776 removeDependency: (actor, workspace, slug, on) => call("remove_dependency", { actor, workspace, slug, on }),
777 graph: (projectId) => call("graph", { projectId }),
778 shortcuts: (workspace, viewer) => call("shortcuts", { workspace, viewer }),
779 pin: (actor, workspace, slug, position) => call("pin", { actor, workspace, slug, position: position ?? null }),
780 unpin: (actor, workspace, slug) => call("unpin", { actor, workspace, slug }),
781 reorderPins: (actor, workspace, slugs) => call("reorder_pins", { actor, workspace, slugs }),
782 visited: (actor, projectId) => call("visited", { actor, projectId }),
783 publicLinks: (repos) => call("public_links", { repos }),
784 };
785}