Skip to content

g1t/packages/contracts/src/clients.ts

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