g1t/packages/contracts/src/clients.ts

633 lines36,993 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 { WorkApi } from "./work";
12import type { RunnersApi } from "./runners";
13
14/** A service binding, as far as these clients need it. */
15export type ServiceBinding = {
16 fetch(input: string, init?: RequestInit): Promise<Response>;
17};
18
19/**
20 * Calls a method on a service that speaks the JSON protocol used by the
21 * Rust services: `POST /rpc/<method>` with the arguments as the body.
22 */
23async function rpc<T>(
24 service: ServiceBinding,
25 method: string,
26 args: object,
27): Promise<T> {
28 // The hostname is ignored; a service binding always reaches its service.
29 const response = await service.fetch(`https://service/rpc/${method}`, {
30 method: "POST",
31 headers: { "content-type": "application/json" },
32 body: JSON.stringify(args),
33 });
34 if (!response.ok) {
35 throw new Error(`${method} failed with status ${response.status}`);
36 }
37 return (await response.json()) as T;
38}
39
40export function identityClient(service: ServiceBinding): IdentityApi {
41 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
42 return {
43 register: (username, email, password, inviteCode, client) =>
44 call("register", { username, email, password, invite_code: inviteCode ?? null, client: client ?? null }),
45 signIn: (username, password, client) => call("sign_in", { username, password, client: client ?? null }),
46 signOut: (sessionToken) => call("sign_out", { sessionToken }),
47 resendVerification: (user) => call("resend_verification", { user }),
48 verifyEmail: (token) => call("verify_email", { token }),
49 requestPasswordReset: (email, client) => call("request_password_reset", { email, client: client ?? null }),
50 resetPassword: (token, password) =>
51 call("reset_password", { token, password }),
52 deviceStart: (clientName) => call("device_start", { clientName }),
53 deviceLookup: (userCode) => call("device_lookup", { userCode }),
54 deviceResolve: (userCode, user, approve) =>
55 call("device_resolve", { userCode, user, approve }),
56 deviceClaim: (deviceCode) => call("device_claim", { deviceCode }),
57 oauthAuthorize: (user, approval) => call("oauth_authorize", { user, ...approval }),
58 oauthExchange: (code, codeVerifier, clientId, redirectUri) =>
59 call("oauth_exchange", { code, codeVerifier, clientId, redirectUri }),
60 oauthRefresh: (refreshToken, clientId) =>
61 call("oauth_refresh", { refreshToken, clientId }),
62 listOAuthGrants: (user) => call("list_oauth_grants", { user }),
63 revokeOAuthGrant: (user, id) => call("revoke_oauth_grant", { user, id }),
64 updateOAuthGrant: (user, id, grant) =>
65 call("update_oauth_grant", { user, id, scopes: grant.scopes }),
66 createWorkspace: (user, slug, name) => call("create_workspace", { user, slug, name }),
67 getWorkspace: (slug) => call("get_workspace", { slug }),
68 listMembers: (slug, viewer) => call("list_members", { slug, viewer }),
69 addMember: (actor, slug, username) => call("add_member", { actor, slug, username }),
70 removeMember: (actor, slug, username) =>
71 call("remove_member", { actor, slug, username }),
72 updateWorkspace: (actor, slug, details) =>
73 call("update_workspace", { actor, slug, ...details }),
74 renameWorkspace: (actor, slug, newSlug) => call("rename_workspace", { actor, slug, newSlug }),
75 checkWorkspaceRename: (actor, slug, newSlug) =>
76 call("check_workspace_rename", { actor, slug, newSlug }),
77 resolveSlug: (slug) => call("resolve_slug", { slug }),
78 deleteWorkspace: (actor, slug, confirm) => call("delete_workspace", { actor, slug, confirm }),
79 checkWorkspaceDeletion: (actor, slug) => call("check_workspace_deletion", { actor, slug }),
80 setWorkspaceAvatar: (actor, slug, image) => call("set_workspace_avatar", { actor, slug, image }),
81 setUserAvatar: (user, image) => call("set_user_avatar", { user, image }),
82 listWorkspaceTokens: (slug, viewer) => call("list_workspace_tokens", { slug, viewer }),
83 createWorkspaceToken: (actor, slug, name, grant) =>
84 call("create_workspace_token", {
85 actor,
86 slug,
87 name,
88 scopes: grant?.scopes ?? null,
89 ttl_seconds: grant?.ttlSeconds ?? null,
90 }),
91 removeWorkspaceToken: (actor, slug, id) =>
92 call("remove_workspace_token", { actor, slug, id }),
93 userForSession: (sessionToken) => call("user_for_session", { sessionToken }),
94 registration: () => call("registration", {}),
95 listInvites: (user) => call("list_invites", { user }),
96 createInvite: (user, options = {}) =>
97 call("create_invite", { user, email: options.email ?? null, workspace: options.workspace ?? null }),
98 revokeInvite: (user, id) => call("revoke_invite", { user, id }),
99 checkInvite: (code, client, options = {}) =>
100 call("check_invite", {
101 code,
102 client: client ?? null,
103 viewer: options.viewer ?? null,
104 any_status: options.anyStatus ?? false,
105 }),
106 acceptInvite: (user, code) => call("accept_invite", { user, code }),
107 inviteMember: (actor, slug, email) => call("invite_member", { actor, slug, email }),
108 workspaceInvites: (slug, viewer) => call("workspace_invites", { slug, viewer }),
109 revokeWorkspaceInvite: (actor, slug, id) => call("revoke_workspace_invite", { actor, slug, id }),
110 requestAccess: (email, about, client) => call("request_access", { email, about, client: client ?? null }),
111 userForGitCredentials: (username, secret) =>
112 call("user_for_git_credentials", { username, secret }),
113 userForAccessToken: (token) => call("user_for_access_token", { token }),
114 userForSshKey: (fingerprint) => call("user_for_ssh_key", { fingerprint }),
115 userByUsername: (username) => call("user_by_username", { username }),
116 usernames: (ids) => call("usernames", { ids }),
117 profile: (username) => call("profile", { username }),
118 updateProfile: (actor, fields) => call("update_profile", { actor, ...fields }),
119 profileWorkspaces: (username, viewer, publicIn) =>
120 call("profile_workspaces", { username, viewer, public: publicIn }),
121 listSshKeys: (user) => call("list_ssh_keys", { user }),
122 addSshKey: (user, title, publicKey) =>
123 call("add_ssh_key", { user, title, publicKey }),
124 removeSshKey: (user, id) => call("remove_ssh_key", { user, id }),
125 listAccessTokens: (user) => call("list_access_tokens", { user }),
126 createAccessToken: (user, name, ttlSeconds, grant) =>
127 call("create_access_token", {
128 user,
129 name,
130 ttlSeconds,
131 scopes: grant?.scopes ?? null,
132 listed: grant?.listed ?? false,
133 }),
134 updateAccessToken: (user, id, grant) =>
135 call("update_access_token", { user, id, scopes: grant.scopes }),
136 createAgentToken: (onBehalfOf, scope, ttlSeconds) =>
137 call("create_agent_token", { onBehalfOf, scope, ttlSeconds }),
138 removeAccessToken: (user, id) => call("remove_access_token", { user, id }),
139 createRunCredential: (input) => call("create_run_credential", input),
140 bindRunCredentials: (tokenHashes, runId) => call("bind_run_credentials", { tokenHashes, runId }),
141 revokeRunCredentials: (target) => call("revoke_run_credentials", target),
142 // Who has access to a repository; see access.ts.
143 repoAccess: (owner, name, viewer) => call("repo_access", { viewer, path: { namespace: owner, name } }),
144 addCollaborator: (actor, owner, name, invitee, role) =>
145 call("add_collaborator", { actor, path: { namespace: owner, name }, invitee, role }),
146 setCollaboratorRole: (actor, owner, name, username, role) =>
147 call("set_collaborator_role", { actor, path: { namespace: owner, name }, username, role }),
148 removeCollaborator: (actor, owner, name, username) =>
149 call("remove_collaborator", { actor, path: { namespace: owner, name }, username }),
150 collaboratorPermission: (viewer, owner, name, username) =>
151 call("collaborator_permission", { viewer, path: { namespace: owner, name }, username }),
152 myRepoInvitations: (user) => call("my_repo_invitations", { user }),
153 respondRepoInvitation: (user, id, accept) => call("respond_repo_invitation", { user, id, accept }),
154 revokeRepoInvitation: (actor, owner, name, id) =>
155 call("revoke_repo_invitation", { actor, path: { namespace: owner, name }, id }),
156 setBasePermission: (actor, slug, base) => call("set_base_permission", { actor, slug, base_permission: base }),
157 outsideCollaborators: (viewer, slug) => call("outside_collaborators", { viewer, slug }),
158 };
159}
160
161/**
162 * The slug a renamed workspace has now, for a `workspace.renamed` handler:
163 * asked of identity by the workspace's id, so that renames delivered twice
164 * or out of order converge. Falls back to the event's `to`.
165 */
166export async function currentWorkspaceSlug(
167 identity: ServiceBinding,
168 renamed: { workspaceId: string; to: string },
169): Promise<string> {
170 const names = await identityClient(identity).usernames([renamed.workspaceId]);
171 return names[renamed.workspaceId] ?? renamed.to;
172}
173
174/** The slugs whose rows move to `current`: the two a rename names, less `current`. */
175export function staleSlugs(renamed: { from: string; to: string }, current: string): string[] {
176 return [...new Set([renamed.from, renamed.to])].filter((slug) => slug !== current);
177}
178
179/**
180 * Where a transferred repository is now, as `namespace/name`, for a
181 * `repo.transferred` handler: asked of repos by id, so transfers delivered
182 * twice or out of order converge. Falls back to the event's destination.
183 */
184export async function currentRepoPath(
185 repos: ServiceBinding,
186 transferred: { repoId: string; name: string; to: string },
187): Promise<string> {
188 const path = await rpc<{ namespace: string; name: string } | null>(repos, "path_by_id", { id: transferred.repoId });
189 return path ? `${path.namespace}/${path.name}` : `${transferred.to}/${transferred.name}`;
190}
191
192/** The paths whose rows move to `current`: the two a transfer names, less `current`. */
193export function stalePaths(transferred: { name: string; from: string; to: string }, current: string): string[] {
194 return [...new Set([transferred.from, transferred.to].map((ns) => `${ns}/${transferred.name}`))].filter(
195 (path) => path !== current,
196 );
197}
198
199/**
200 * A repository's path change, from `repo.transferred` or `repo.renamed`,
201 * read the same way: the two paths (`namespace/name`) the event names, old
202 * then new. Null for any other event.
203 */
204export type RepoMove = { repoId: string; paths: [string, string] };
205
206export function repoMove(event: { type: string; data: unknown }): RepoMove | null {
207 const data = event.data as Record<string, string>;
208 if (event.type === "repo.transferred") {
209 return { repoId: data.repoId!, paths: [`${data.from}/${data.name}`, `${data.to}/${data.name}`] };
210 }
211 if (event.type === "repo.renamed") {
212 return { repoId: data.repoId!, paths: [`${data.namespace}/${data.from}`, `${data.namespace}/${data.to}`] };
213 }
214 return null;
215}
216
217/**
218 * Where a moved repository is now, as `namespace/name`: asked of repos by
219 * id, so moves delivered twice or out of order converge. Falls back to the
220 * event's new path.
221 */
222export async function currentMovedPath(repos: ServiceBinding, move: RepoMove): Promise<string> {
223 const path = await rpc<{ namespace: string; name: string } | null>(repos, "path_by_id", { id: move.repoId });
224 return path ? `${path.namespace}/${path.name}` : move.paths[1];
225}
226
227/** The paths whose rows move to `current`: the two a move names, less `current`. */
228export function staleMovedPaths(move: RepoMove, current: string): string[] {
229 return [...new Set(move.paths)].filter((path) => path !== current);
230}
231
232/** Staff-only identity. Only sudo binds to it; see `IdentityAdminApi`. */
233export function identityAdminClient(service: ServiceBinding): IdentityAdminApi {
234 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
235 return {
236 workspaces: (query) => call("admin_workspaces", { query: query ?? null }),
237 workspace: (slug) => call("admin_workspace", { slug }),
238 waitlist: (query, status) => call("admin_waitlist", { query: query ?? null, status: status ?? null }),
239 waitlistPending: () => call("admin_waitlist_pending", {}),
240 decideWaitlist: (id, approve, staff, note) => call("admin_decide_waitlist", { id, approve, staff, note: note ?? null }),
241 invites: (query) => call("admin_invites", { query: query ?? null }),
242 revokeInvite: (id, staff) => call("admin_revoke_invite", { id, staff }),
243 mintInvite: (email, staff) => call("admin_mint_invite", { email, staff }),
244 grantInvites: (target, name, amount, note, staff) =>
245 call("admin_grant_invites", { target, name, amount, note, staff }),
246 inviteTree: (username) => call("admin_invite_tree", { username }),
247 workspaceInvites: (slug) => call("admin_workspace_invites", { slug }),
248 deletedWorkspaces: () => call("admin_deleted_workspaces", {}),
249 restoreWorkspace: (workspaceId, staff) => call("admin_restore_workspace", { workspaceId, staff }),
250 purgeWorkspace: (workspaceId, staff, confirm) => call("admin_purge_workspace", { workspaceId, staff, confirm }),
251 };
252}
253
254export function reposClient(service: ServiceBinding): ReposApi {
255 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
256 return {
257 get: (path, viewer) => call("get", { path, viewer }),
258 getById: (id, viewer) => call("get_by_id", { id, viewer }),
259 readable: (ids, viewer) => call("readable", { ids, viewer }),
260 publicNamespaces: (ownerId) => call("public_namespaces", { ownerId }),
261 list: (viewer, options = {}) => call("list", { viewer, ...options }),
262 create: (owner, input) => call("create", { owner, ...input }),
263 update: (actor, path, changes) => call("update", { actor, path, ...changes }),
264 transfer: (actor, path, to) => call("transfer", { actor, path, to }),
265 delete: (actor, path, confirm) => call("delete", { actor, path, confirm }),
266 deleted: (viewer, namespace) => call("deleted", { viewer, namespace }),
267 restore: (actor, path) => call("restore", { actor, path }),
268 purge: (actor, path, confirm) => call("purge", { actor, path, confirm }),
269 rename: (actor, path, name) => call("rename", { actor, path, name }),
270 archive: (actor, path, archived) => call("archive", { actor, path, archived }),
271 setVisibility: (actor, path, isPrivate, confirm) => call("set_visibility", { actor, path, isPrivate, confirm }),
272 setDefaultBranch: (actor, path, branch) => call("set_default_branch", { actor, path, branch }),
273 renameBranch: (actor, path, from, to) => call("rename_branch", { actor, path, from, to }),
274 resolveBranch: (repoId, branch) => call("resolve_branch", { repoId, branch }),
275 statusById: (id) => call("status_by_id", { id }),
276 resolvePath: (path) => call("resolve_path", { path }),
277 tree: (path, viewer, ref, treePath) =>
278 call("tree", { path, viewer, ref, treePath }),
279 blob: (path, viewer, ref, filePath) =>
280 call("blob", { path, viewer, ref, filePath }),
281 log: (path, viewer, ref, limit) => call("log", { path, viewer, ref, limit }),
282 blame: (path, viewer, ref, filePath) => call("blame", { path, viewer, ref, filePath }),
283 forkForPull: (sourceId, pullId, actor) =>
284 call("fork_for_pull", { sourceId, pullId, actor }),
285 gitAccess: (path, viewer, service) =>
286 call("git_access", { path, viewer, service }),
287 branches: (path, viewer) => call("branches", { path, viewer }),
288 listFiles: (repoId, ref, limit) => call("list_files", { repoId, ref, skipDirs: [], limit }),
289 rawBlobs: (repoId, hashes, maxBytes) => call("raw_blobs", { repoId, hashes, maxBytes }),
290 commitFile: (repo, actor, file) => call("commit_file", { repo, actor, ...file }),
291 land: (sourceId, actor, branch) => call("land", { sourceId, actor, branch }),
292 compare: (repoId, viewer, base, head) => call("compare", { repoId, viewer, base, head }),
293 };
294}
295
296export function workClient(service: ServiceBinding): WorkApi {
297 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
298 return {
299 openIssue: (actor, repo, input) => call("open_issue", { actor, repo, ...input }),
300 delegateIssue: (actor, repo, input) => call("delegate_issue", { actor, repo, ...input }),
301 listIssues: (repo, viewer, filter = {}) => call("list_issues", { repo, viewer, ...filter }),
302 getIssue: (repo, number, viewer) => call("get_issue", { repo, number, viewer }),
303 updateIssue: (actor, repo, number, input) =>
304 call("update_issue", { actor, repo, number, ...input }),
305 closeIssue: (actor, repo, number, reason) =>
306 call("close_issue", { actor, repo, number, reason }),
307 reopenIssue: (actor, repo, number) => call("reopen_issue", { actor, repo, number }),
308 listLabels: (repo, viewer) => call("list_labels", { repo, viewer }),
309 counts: (repo, viewer) => call("counts", { repo, viewer }),
310 addComment: (actor, repo, number, comment) =>
311 call("add_comment", { actor, repo, number, ...comment }),
312 startChecks: (pullId) => call("start_checks", { pullId }),
313 reportChecks: (runId, token, report) =>
314 call("report_checks", { runId, token, ...report }),
315 startReview: (pullId) => call("start_review", { pullId }),
316 failReview: (runId, token, error) => call("report_review", { runId, token, error }),
317 startMergecheck: (pullId) => call("start_mergecheck", { pullId }),
318 failMergecheck: (pullId, token, error) => call("report_mergecheck", { pullId, token, error }),
319 advance: (pullId) => call("advance", { pullId }),
320 stall: (pullId, reason) => call("stall", { pullId, reason }),
321 managedPulls: (repoId) => call("managed_pulls", { repoId }),
322 queue: (repo, viewer) => call("queue", { repo, viewer }),
323 queueBuild: (repoId) => call("queue_build", { repoId }),
324 failQueue: (entryId, token, error) => call("report_queue", { entryId, token, error }),
325 removeFromQueue: (actor, repo, number) => call("remove_from_queue", { actor, repo, number }),
326 messageAgent: (actor, repo, number, body) => call("message_agent", { actor, repo, number, body }),
327 catchUpJob: (pullId) => call("catch_up_job", { pullId }),
328 wakeForMessages: (pullId) => call("wake_for_messages", { pullId }),
329 getSettings: (repo, viewer) => call("get_settings", { repo, viewer }),
330 seenChecks: (repo, viewer) => call("seen_checks", { repo, viewer }),
331 updateSettings: (actor, repo, settings) =>
332 call("update_settings", { actor, repo, settings }),
333 openPull: (actor, repo, input) => call("open_pull", { actor, repo, ...input }),
334 listPulls: (repo, viewer, state) => call("list_pulls", { repo, viewer, state }),
335 pullsForRepos: (repoIds, viewer, limit) => call("pulls_for_repos", { repoIds, viewer, limit }),
336 getPull: (repo, number, viewer) => call("get_pull", { repo, number, viewer }),
337 updatePull: (actor, repo, number, changes) =>
338 call("update_pull", { actor, repo, number, ...changes }),
339 catchUpPull: (actor, repo, number) => call("catch_up_pull", { actor, repo, number }),
340 readyPull: (actor, repo, number, summary) =>
341 call("ready_pull", { actor, repo, number, summary }),
342 closePull: (actor, repo, number) => call("close_pull", { actor, repo, number }),
343 mergePull: (actor, repo, number, options = {}) =>
344 call("merge_pull", { actor, repo, number, ...options }),
345 listActivePulls: (viewer) => call("list_active_pulls", { viewer }),
346 byAuthor: (username, viewer, filter = {}) => call("by_author", { username, viewer, ...filter }),
347 startPlan: (actor, repo, brief) => call("start_plan", { actor, repo, brief }),
348 failPlan: (planId, token, error) => call("report_plan", { planId, token, error }),
349 getPlan: (repo, viewer, id) => call("get_plan", { repo, viewer, id }),
350 listPlans: (repo, viewer) => call("list_plans", { repo, viewer }),
351 applyPlan: (actor, repo, id, options = {}) =>
352 call("apply_plan", { actor, repo, id, ...options }),
353 queueIssue: (actor, repo, number, queued) =>
354 call("queue_issue", { actor, repo, number, queued }),
355 readyIssues: (repoId) => call("ready_issues", { repoId }),
356 listAssignedIssues: (viewer) => call("list_assigned_issues", { viewer }),
357 appendSession: (actor, repo, number, entries) =>
358 call("append_session", { actor, repo, number, entries }),
359 readSession: (repo, number, viewer, afterSeq = 0) =>
360 call("read_session", { repo, number, viewer, afterSeq }),
361 };
362}
363
364export function billingClient(service: ServiceBinding): BillingApi {
365 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
366 return {
367 status: () => call("status", {}),
368 account: (workspace, viewer) => call("account", { workspace, viewer }),
369 ledger: (workspace, viewer) => call("ledger", { workspace, viewer }),
370 statement: (workspace, viewer, month = null, group = "day") => call("statement", { workspace, viewer, month, group }),
371 statementEntries: (workspace, viewer, filter) =>
372 call("statement_entries", {
373 workspace,
374 viewer,
375 month: filter.month,
376 kind: filter.kind,
377 day: filter.day ?? null,
378 project: filter.project ?? null,
379 before: filter.before ?? null,
380 }),
381 usage: (workspace, viewer, since) => call("usage", { workspace, viewer, since }),
382 tokenUsage: (workspace, viewer, options = {}) =>
383 call("token_usage", { workspace, viewer, person: options.person ?? null, days: options.days ?? null }),
384 recordTokens: (usage) => call("record_tokens", usage),
385 checkout: (actor, workspace, amountCents, returnUrl, method = "card") =>
386 call("checkout", { actor, workspace, amountCents, returnUrl, method }),
387 confirm: (workspace, viewer, session) => call("confirm", { workspace, viewer, session }),
388 canStart: (workspace) => call("can_start", { workspace }),
389 trial: (workspace, exempt) => call("trial", { workspace, exempt }),
390 startRun: (run) => call("start_run", run),
391 features: (workspace, viewer) => call("features", { workspace, viewer }),
392 subscribe: (actor, workspace, feature, returnUrl) =>
393 call("subscribe", { actor, workspace, feature, returnUrl }),
394 confirmSubscription: (workspace, viewer, session) =>
395 call("confirm_subscription", { workspace, viewer, session }),
396 cancelSubscription: (actor, workspace, feature, resume = false) =>
397 call("cancel_subscription", { actor, workspace, feature, resume }),
398 hasFeature: (workspace, feature) => call("has_feature", { workspace, feature }),
399 chargeFeature: (charge) => call("charge_feature", charge),
400 billingPortal: (actor, workspace, returnUrl) => call("billing_portal", { actor, workspace, return_url: returnUrl }),
401 recordSandbox: (usage) => call("record_sandbox", usage),
402 limit: (workspace, viewer) => call("limit", { workspace, viewer }),
403 checkLimit: (workspace) => call("check_limit", { workspace }),
404 prices: () => call("prices", {}),
405 notePending: (workspace, source, costMicros, detail = null) => call("note_pending", { workspace, source, costMicros, detail }),
406 usageMeters: (workspace, viewer) => call("usage_meters", { workspace, viewer }),
407 setSpendLimit: (actor, workspace, spendLimitMicros, useFullLimit = false, raiseOnce = false) =>
408 call("set_spend_limit", { actor, workspace, spendLimitMicros, use_full_limit: useFullLimit, raise_once: raiseOnce }),
409 invoices: (workspace, viewer) => call("invoices", { workspace, viewer }),
410 entitlements: (workspace) => call("entitlements", { workspace }),
411 reserve: (reservation) => call("reserve", reservation),
412 settle: (reservationId, actualMicros) => call("settle", { reservationId, actualMicros }),
413 cardCheck: (actor, workspace, returnUrl) => call("card_check", { actor, workspace, returnUrl }),
414 confirmCardCheck: (workspace, viewer, session) => call("confirm_card_check", { workspace, viewer, session }),
415 requestLimit: (actor, workspace, request) => call("request_limit", { actor, workspace, ...request }),
416 limitRequests: (workspace, viewer) => call("limit_requests", { workspace, viewer }),
417 confirmSpike: (actor, workspace, keepGoing) => call("confirm_spike", { actor, workspace, keepGoing }),
418 setCaps: (actor, workspace, caps) => call("set_caps", { actor, workspace, ...caps }),
419 };
420}
421
422export function billingAdminClient(service: ServiceBinding): BillingAdminApi {
423 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
424 return {
425 accounts: (query) => call("admin_accounts", { query: query ?? null }),
426 account: (id) => call("admin_account", { id }),
427 setTerms: (id, terms, by) => call("admin_set_terms", { id, terms, by }),
428 setAllowances: (id, allowances, note, by) => call("admin_set_allowances", { id, allowances, note, by }),
429 createEnterprise: (name, workspaces, by) => call("admin_create_enterprise", { name, workspaces, by }),
430 attach: (workspace, account, by) => call("admin_attach", { workspace, account, by }),
431 credit: (workspace, amountMicros, note, by) => call("admin_credit", { workspace, amount_micros: amountMicros, note, by }),
432 billingLink: (workspace, by) => call("admin_billing_link", { workspace, by }),
433 stripe: (fix = false, by) => call("admin_stripe", { fix, by: by ?? null }),
434 enterpriseBilling: (id, email, by) => call("admin_enterprise_billing", { id, email, by }),
435 invoiceEnterprise: (id, by) => call("admin_invoice_enterprise", { id, by }),
436 accountsFor: (workspaces) => call("admin_accounts", { query: null, workspaces }),
437 signals: () => call("admin_signals", {}),
438 overview: () => call("admin_overview", {}),
439 sales: (workspace) => call("admin_sales", { workspace }),
440 setSales: (workspace, record, by) =>
441 call("admin_set_sales", {
442 workspace,
443 stage: record.stage,
444 owner: record.owner ?? null,
445 next_step: record.nextStep ?? null,
446 next_at: record.nextAt ?? null,
447 by,
448 }),
449 addNote: (workspace, text, by) => call("admin_add_note", { workspace, text, by }),
450 workspaceInvoices: (workspace) => call("admin_workspace_invoices", { workspace }),
451 allInvoices: (filter = {}) => call("admin_invoices", { status: filter.status ?? null, month: filter.month ?? null }),
452 audit: (filter = {}) =>
453 call("admin_audit", { by: filter.by ?? null, action: filter.action ?? null, before: filter.before ?? null }),
454 limitRequests: (status = "open") => call("admin_limit_requests", { status }),
455 decideLimitRequest: (id, decision, amountMicros, note, by) =>
456 call("admin_decide_limit_request", { id, decision, amount_micros: amountMicros, note, by }),
457 overages: () => call("admin_overages", {}),
458 goodwill: (workspace, amountMicros, reason, by, day = null) =>
459 call("admin_goodwill", { workspace, amount_micros: amountMicros, reason, by, day }),
460 velocity: () => call("admin_velocity", {}),
461 recordPayment: (workspace, amountMicros, reference, note, by) =>
462 call("admin_record_payment", { workspace, amount_micros: amountMicros, reference, note, by }),
463 costs: (days) => call("admin_costs", { days: days ?? null }),
464 costAlerts: () => call("admin_cost_alerts", {}),
465 spendCaps: () => call("admin_spend_caps", {}),
466 liftBreaker: (note, by) => call("admin_lift_breaker", { note, by }),
467 decideProposal: (id, decision, note, by) => call("admin_decide_proposal", { id, decision, note, by }),
468 setCostSettings: (settings, by) => call("admin_set_cost_settings", { settings, by }),
469 setCostMapping: (mapping, by) =>
470 call("admin_set_cost_mapping", {
471 product: mapping.product,
472 meter: mapping.meter,
473 bucket: mapping.bucket ?? "",
474 price_meter: mapping.priceMeter ?? null,
475 own_meter: mapping.ownMeter ?? null,
476 scale_to_own: mapping.scaleToOwn ?? false,
477 drift_percent: mapping.driftPercent ?? null,
478 note: mapping.note ?? "",
479 remove: mapping.remove ?? false,
480 by,
481 }),
482 runCosts: (by) => call("admin_run_costs", { by }),
483 };
484}
485
486export function eventsClient(service: ServiceBinding): EventsApi {
487 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
488 return {
489 publish: (events) => call("publish", { events }),
490 list: (query) => call("list", query),
491 };
492}
493
494export function integrationsClient(service: ServiceBinding): IntegrationsApi {
495 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
496 return {
497 list: (workspace, viewer) => call("list", { workspace, viewer }),
498 connect: (actor, workspace, input) => call("connect", { actor, workspace, ...input }),
499 update: (actor, workspace, id, input) => call("update", { actor, workspace, id, ...input }),
500 disconnect: (actor, workspace, id) => call("disconnect", { actor, workspace, id }),
501 test: (actor, workspace, id) => call("test", { actor, workspace, id }),
502 deliveries: (workspace, viewer, id) => call("deliveries", { workspace, viewer, id }),
503 resolve: (workspace, viewer, reference) => call("resolve", { workspace, viewer, reference }),
504 references: (workspace, text, limit) => call("references", { workspace, text, limit }),
505 import: (actor, repo, reference, assign) => call("import", { actor, repo, reference, assign }),
506 links: (repo, number) => call("links", { repo, number }),
507 modelProvider: (workspace) => call("model_provider", { workspace }),
508 openModelSession: (run) => call("open_model_session", run),
509 modelUpstream: (token) => call("model_upstream", { token }),
510 closeModelSessions: (tokenHashes) => call("close_model_sessions", { token_hashes: tokenHashes }),
511 routes: (workspace, viewer) => call("routes", { workspace, viewer }),
512 setRoutes: (actor, workspace, routes) => call("set_routes", { actor, workspace, routes }),
513 };
514}
515
516export function webhooksClient(service: ServiceBinding): WebhooksApi {
517 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
518 return {
519 list: (viewer, owner) => call("list", { viewer, ...owner }),
520 create: (actor, owner, input) => call("create", { actor, ...owner, ...input }),
521 update: (actor, owner, id, input) => call("update", { actor, ...owner, id, ...input }),
522 delete: (actor, owner, id) => call("delete", { actor, ...owner, id }),
523 ping: (actor, owner, id) => call("ping", { actor, ...owner, id }),
524 deliveries: (viewer, owner, id) => call("deliveries", { viewer, ...owner, id }),
525 redeliver: (actor, owner, deliveryId) => call("redeliver", { actor, ...owner, deliveryId }),
526 };
527}
528
529export function actionsClient(service: ServiceBinding): ActionsApi {
530 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
531 return {
532 workflows: (repo, viewer) => call("workflows", { repo, viewer }),
533 runs: (repo, viewer, filter = {}) => call("runs", { repo, viewer, ...filter }),
534 run: (repo, viewer, id) => call("run", { repo, viewer, id }),
535 logs: (repo, viewer, job, after = 0) => call("logs", { repo, viewer, job, after }),
536 dispatch: (actor, repo, workflow, ref, inputs) => call("dispatch", { actor, repo, workflow, ref, inputs }),
537 cancel: (actor, repo, id) => call("cancel", { actor, repo, id }),
538 rerun: (actor, repo, id, failedOnly = false) => call("rerun", { actor, repo, id, failed_only: failedOnly }),
539 setWorkflowEnabled: (actor, repo, workflow, enabled) =>
540 call("set_workflow_enabled", { actor, repo, workflow, enabled }),
541 settings: (actor, owner, kind) => call("settings", { actor, ...owner, kind }),
542 setSetting: (actor, owner, kind, name, value, options = {}) =>
543 call("set_setting", { actor, ...owner, kind, name, value, ...options }),
544 deleteSetting: (actor, owner, kind, name, id) => call("delete_setting", { actor, ...owner, kind, name, id }),
545 };
546}
547
548
549/** Self-hosted runners, kept by the actions service. */
550export function runnersClient(service: ServiceBinding): RunnersApi {
551 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
552 return {
553 stuck: (viewer) => call("stuck_jobs", { viewer }),
554 list: (actor, owner) => call("runners", { actor, ...owner }),
555 createToken: (actor, owner, group) => call("create_registration_token", { actor, ...owner, group }),
556 remove: (actor, owner, id) => call("remove_runner", { actor, ...owner, id }),
557 groups: (actor, workspace) => call("runner_groups", { actor, workspace }),
558 setGroup: (actor, workspace, group) => call("set_runner_group", { actor, workspace, ...group }),
559 deleteGroup: (actor, workspace, id) => call("delete_runner_group", { actor, workspace, id }),
560 settings: (actor, owner) => call("runner_settings", { actor, ...owner }),
561 setSettings: (actor, owner, change) => call("set_runner_settings", { actor, ...owner, ...change }),
562 };
563}
564
565export function deploymentsClient(service: ServiceBinding): DeploymentsApi {
566 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
567 return {
568 settings: (project, viewer) => call("settings", { project, viewer }),
569 updateSettings: (actor, project, changes) => call("update_settings", { actor, project, changes }),
570 list: (project, viewer) => call("list", { project, viewer }),
571 get: (project, id, viewer) => call("get", { project, id, viewer }),
572 redeploy: (actor, project, branch) => call("redeploy", { actor, project, branch }),
573 takeDown: (actor, project, branch) => call("take_down", { actor, project, branch }),
574 stack: (actor, project, branch) => call("stack", { actor, project, branch }),
575 overview: (workspace, viewer) => call("overview", { workspace, viewer }),
576 usage: (workspace, viewer) => call("usage", { workspace, viewer }),
577 domains: (project, viewer) => call("domains", { project, viewer }),
578 addDomain: (actor, project, hostname, options = {}) =>
579 call("add_domain", { actor, project, hostname, twin: !!options.twin }),
580 removeDomain: (actor, project, id) => call("remove_domain", { actor, project, id }),
581 refreshDomain: (actor, project, id) => call("refresh_domain", { actor, project, id }),
582 };
583}
584
585/** Packages: the registries beside the code (services/packages). */
586export function packagesClient(service: ServiceBinding): PackagesApi {
587 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
588 return {
589 list: (workspace, viewer, filter = {}) =>
590 call("list_packages", {
591 workspace,
592 viewer,
593 ecosystem: filter.ecosystem ?? null,
594 repo_id: filter.repoId ?? null,
595 query: filter.query ?? null,
596 }),
597 get: (workspace, ecosystem, name, viewer) => call("get_package", { workspace, ecosystem, name, viewer }),
598 deleteVersion: (actor, workspace, ecosystem, name, version, surface) =>
599 call("delete_version", { actor, workspace, ecosystem, name, version, surface: surface ?? null }),
600 deletePackage: (actor, workspace, ecosystem, name, surface) =>
601 call("delete_package", { actor, workspace, ecosystem, name, surface: surface ?? null }),
602 set: (actor, workspace, ecosystem, name, change, surface) =>
603 call("set_package", {
604 actor,
605 workspace,
606 ecosystem,
607 name,
608 visibility: change.visibility ?? null,
609 link: change.link ?? null,
610 unlink: change.unlink ?? false,
611 surface: surface ?? null,
612 }),
613 storage: (workspace) => call("storage", { workspace }),
614 storageAll: () => call("storage_all", {}),
615 syncComposer: (repoId) => call("sync_composer", { repo_id: repoId }),
616 };
617}
618
619export function projectsClient(service: ServiceBinding): ProjectsApi {
620 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
621 return {
622 list: (workspace, viewer) => call("list", { workspace, viewer }),
623 get: (workspace, slug, viewer) => call("get", { workspace, slug, viewer }),
624 byRepo: (repoId) => call("by_repo", { repoId }),
625 create: (actor, workspace, input) => call("create", { actor, workspace, input }),
626 update: (actor, workspace, slug, changes) => call("update", { actor, workspace, slug, changes }),
627 deploymentsChanged: (projectId, enabled) => call("deployments_changed", { projectId, enabled }),
628 dependencies: (workspace, slug, viewer) => call("dependencies", { workspace, slug, viewer }),
629 addDependency: (actor, workspace, slug, on, as) => call("add_dependency", { actor, workspace, slug, on, as }),
630 removeDependency: (actor, workspace, slug, on) => call("remove_dependency", { actor, workspace, slug, on }),
631 graph: (projectId) => call("graph", { projectId }),
632 };
633}