flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/packages/contracts/src/clients.ts

395 lines22,730 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 { WebhooksApi } from "./webhooks";
9import type { ReposApi } from "./repos";
10import type { WorkApi } from "./work";
11
12/** A service binding, as far as these clients need it. */
13export type ServiceBinding = {
14 fetch(input: string, init?: RequestInit): Promise<Response>;
15};
16
17/**
18 * Calls a method on a service that speaks the JSON protocol used by the
19 * Rust services: `POST /rpc/<method>` with the arguments as the body.
20 */
21async function rpc<T>(
22 service: ServiceBinding,
23 method: string,
24 args: object,
25): Promise<T> {
26 // The hostname is ignored; a service binding always reaches its service.
27 const response = await service.fetch(`https://service/rpc/${method}`, {
28 method: "POST",
29 headers: { "content-type": "application/json" },
30 body: JSON.stringify(args),
31 });
32 if (!response.ok) {
33 throw new Error(`${method} failed with status ${response.status}`);
34 }
35 return (await response.json()) as T;
36}
37
38export function identityClient(service: ServiceBinding): IdentityApi {
39 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
40 return {
41 register: (username, email, password) =>
42 call("register", { username, email, password }),
43 signIn: (username, password) => call("sign_in", { username, password }),
44 signOut: (sessionToken) => call("sign_out", { sessionToken }),
45 resendVerification: (user) => call("resend_verification", { user }),
46 verifyEmail: (token) => call("verify_email", { token }),
47 requestPasswordReset: (email) => call("request_password_reset", { email }),
48 resetPassword: (token, password) =>
49 call("reset_password", { token, password }),
50 deviceStart: (clientName) => call("device_start", { clientName }),
51 deviceLookup: (userCode) => call("device_lookup", { userCode }),
52 deviceResolve: (userCode, user, approve) =>
53 call("device_resolve", { userCode, user, approve }),
54 deviceClaim: (deviceCode) => call("device_claim", { deviceCode }),
55 oauthAuthorize: (user, approval) => call("oauth_authorize", { user, ...approval }),
56 oauthExchange: (code, codeVerifier, clientId, redirectUri) =>
57 call("oauth_exchange", { code, codeVerifier, clientId, redirectUri }),
58 oauthRefresh: (refreshToken, clientId) =>
59 call("oauth_refresh", { refreshToken, clientId }),
60 listOAuthGrants: (user) => call("list_oauth_grants", { user }),
61 revokeOAuthGrant: (user, id) => call("revoke_oauth_grant", { user, id }),
62 createWorkspace: (user, slug, name) => call("create_workspace", { user, slug, name }),
63 getWorkspace: (slug) => call("get_workspace", { slug }),
64 listMembers: (slug, viewer) => call("list_members", { slug, viewer }),
65 addMember: (actor, slug, username) => call("add_member", { actor, slug, username }),
66 removeMember: (actor, slug, username) =>
67 call("remove_member", { actor, slug, username }),
68 updateWorkspace: (actor, slug, details) =>
69 call("update_workspace", { actor, slug, ...details }),
70 renameWorkspace: (actor, slug, newSlug) => call("rename_workspace", { actor, slug, newSlug }),
71 checkWorkspaceRename: (actor, slug, newSlug) =>
72 call("check_workspace_rename", { actor, slug, newSlug }),
73 resolveSlug: (slug) => call("resolve_slug", { slug }),
74 setWorkspaceAvatar: (actor, slug, image) => call("set_workspace_avatar", { actor, slug, image }),
75 setUserAvatar: (user, image) => call("set_user_avatar", { user, image }),
76 listWorkspaceTokens: (slug, viewer) => call("list_workspace_tokens", { slug, viewer }),
77 createWorkspaceToken: (actor, slug, name) =>
78 call("create_workspace_token", { actor, slug, name }),
79 removeWorkspaceToken: (actor, slug, id) =>
80 call("remove_workspace_token", { actor, slug, id }),
81 userForSession: (sessionToken) => call("user_for_session", { sessionToken }),
82 userForGitCredentials: (username, secret) =>
83 call("user_for_git_credentials", { username, secret }),
84 userForAccessToken: (token) => call("user_for_access_token", { token }),
85 userForSshKey: (fingerprint) => call("user_for_ssh_key", { fingerprint }),
86 userByUsername: (username) => call("user_by_username", { username }),
87 usernames: (ids) => call("usernames", { ids }),
88 profile: (username) => call("profile", { username }),
89 updateProfile: (actor, fields) => call("update_profile", { actor, ...fields }),
90 profileWorkspaces: (username, viewer, publicIn) =>
91 call("profile_workspaces", { username, viewer, public: publicIn }),
92 listSshKeys: (user) => call("list_ssh_keys", { user }),
93 addSshKey: (user, title, publicKey) =>
94 call("add_ssh_key", { user, title, publicKey }),
95 removeSshKey: (user, id) => call("remove_ssh_key", { user, id }),
96 listAccessTokens: (user) => call("list_access_tokens", { user }),
97 createAccessToken: (user, name, ttlSeconds) =>
98 call("create_access_token", { user, name, ttlSeconds }),
99 createAgentToken: (onBehalfOf, scope, ttlSeconds) =>
100 call("create_agent_token", { onBehalfOf, scope, ttlSeconds }),
101 removeAccessToken: (user, id) => call("remove_access_token", { user, id }),
102 };
103}
104
105/**
106 * The slug a renamed workspace has now, for a `workspace.renamed` handler:
107 * asked of identity by the workspace's id, so that renames delivered twice
108 * or out of order converge. Falls back to the event's `to`.
109 */
110export async function currentWorkspaceSlug(
111 identity: ServiceBinding,
112 renamed: { workspaceId: string; to: string },
113): Promise<string> {
114 const names = await identityClient(identity).usernames([renamed.workspaceId]);
115 return names[renamed.workspaceId] ?? renamed.to;
116}
117
118/** The slugs whose rows move to `current`: the two a rename names, less `current`. */
119export function staleSlugs(renamed: { from: string; to: string }, current: string): string[] {
120 return [...new Set([renamed.from, renamed.to])].filter((slug) => slug !== current);
121}
122
123/** Staff-only identity. Only sudo binds to it; see `IdentityAdminApi`. */
124export function identityAdminClient(service: ServiceBinding): IdentityAdminApi {
125 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
126 return {
127 workspaces: (query) => call("admin_workspaces", { query: query ?? null }),
128 workspace: (slug) => call("admin_workspace", { slug }),
129 };
130}
131
132export function reposClient(service: ServiceBinding): ReposApi {
133 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
134 return {
135 get: (path, viewer) => call("get", { path, viewer }),
136 getById: (id, viewer) => call("get_by_id", { id, viewer }),
137 publicNamespaces: (ownerId) => call("public_namespaces", { ownerId }),
138 list: (viewer, options = {}) => call("list", { viewer, ...options }),
139 create: (owner, input) => call("create", { owner, ...input }),
140 update: (actor, path, changes) => call("update", { actor, path, ...changes }),
141 tree: (path, viewer, ref, treePath) =>
142 call("tree", { path, viewer, ref, treePath }),
143 blob: (path, viewer, ref, filePath) =>
144 call("blob", { path, viewer, ref, filePath }),
145 log: (path, viewer, ref, limit) => call("log", { path, viewer, ref, limit }),
146 blame: (path, viewer, ref, filePath) => call("blame", { path, viewer, ref, filePath }),
147 forkForPull: (sourceId, pullId, actor) =>
148 call("fork_for_pull", { sourceId, pullId, actor }),
149 gitAccess: (path, viewer, service) =>
150 call("git_access", { path, viewer, service }),
151 branches: (path, viewer) => call("branches", { path, viewer }),
152 land: (sourceId, actor, branch) => call("land", { sourceId, actor, branch }),
153 compare: (repoId, viewer, base, head) => call("compare", { repoId, viewer, base, head }),
154 };
155}
156
157export function workClient(service: ServiceBinding): WorkApi {
158 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
159 return {
160 openIssue: (actor, repo, input) => call("open_issue", { actor, repo, ...input }),
161 listIssues: (repo, viewer, filter = {}) => call("list_issues", { repo, viewer, ...filter }),
162 getIssue: (repo, number, viewer) => call("get_issue", { repo, number, viewer }),
163 updateIssue: (actor, repo, number, input) =>
164 call("update_issue", { actor, repo, number, ...input }),
165 closeIssue: (actor, repo, number, reason) =>
166 call("close_issue", { actor, repo, number, reason }),
167 reopenIssue: (actor, repo, number) => call("reopen_issue", { actor, repo, number }),
168 listLabels: (repo, viewer) => call("list_labels", { repo, viewer }),
169 counts: (repo, viewer) => call("counts", { repo, viewer }),
170 addComment: (actor, repo, number, comment) =>
171 call("add_comment", { actor, repo, number, ...comment }),
172 startChecks: (pullId) => call("start_checks", { pullId }),
173 reportChecks: (runId, token, report) =>
174 call("report_checks", { runId, token, ...report }),
175 startReview: (pullId) => call("start_review", { pullId }),
176 failReview: (runId, token, error) => call("report_review", { runId, token, error }),
177 startMergecheck: (pullId) => call("start_mergecheck", { pullId }),
178 failMergecheck: (pullId, token, error) => call("report_mergecheck", { pullId, token, error }),
179 advance: (pullId) => call("advance", { pullId }),
180 stall: (pullId, reason) => call("stall", { pullId, reason }),
181 managedPulls: (repoId) => call("managed_pulls", { repoId }),
182 queue: (repo, viewer) => call("queue", { repo, viewer }),
183 queueBuild: (repoId) => call("queue_build", { repoId }),
184 failQueue: (entryId, token, error) => call("report_queue", { entryId, token, error }),
185 removeFromQueue: (actor, repo, number) => call("remove_from_queue", { actor, repo, number }),
186 messageAgent: (actor, repo, number, body) => call("message_agent", { actor, repo, number, body }),
187 catchUpJob: (pullId) => call("catch_up_job", { pullId }),
188 wakeForMessages: (pullId) => call("wake_for_messages", { pullId }),
189 getSettings: (repo, viewer) => call("get_settings", { repo, viewer }),
190 updateSettings: (actor, repo, settings) =>
191 call("update_settings", { actor, repo, settings }),
192 openPull: (actor, repo, input) => call("open_pull", { actor, repo, ...input }),
193 listPulls: (repo, viewer, state) => call("list_pulls", { repo, viewer, state }),
194 getPull: (repo, number, viewer) => call("get_pull", { repo, number, viewer }),
195 updatePull: (actor, repo, number, changes) =>
196 call("update_pull", { actor, repo, number, ...changes }),
197 readyPull: (actor, repo, number, summary) =>
198 call("ready_pull", { actor, repo, number, summary }),
199 closePull: (actor, repo, number) => call("close_pull", { actor, repo, number }),
200 mergePull: (actor, repo, number, options = {}) =>
201 call("merge_pull", { actor, repo, number, ...options }),
202 listActivePulls: (viewer) => call("list_active_pulls", { viewer }),
203 byAuthor: (username, viewer, filter = {}) => call("by_author", { username, viewer, ...filter }),
204 startPlan: (actor, repo, brief) => call("start_plan", { actor, repo, brief }),
205 failPlan: (planId, token, error) => call("report_plan", { planId, token, error }),
206 getPlan: (repo, viewer, id) => call("get_plan", { repo, viewer, id }),
207 listPlans: (repo, viewer) => call("list_plans", { repo, viewer }),
208 applyPlan: (actor, repo, id, options = {}) =>
209 call("apply_plan", { actor, repo, id, ...options }),
210 queueIssue: (actor, repo, number, queued) =>
211 call("queue_issue", { actor, repo, number, queued }),
212 readyIssues: (repoId) => call("ready_issues", { repoId }),
213 listAssignedIssues: (viewer) => call("list_assigned_issues", { viewer }),
214 appendSession: (actor, repo, number, entries) =>
215 call("append_session", { actor, repo, number, entries }),
216 readSession: (repo, number, viewer, afterSeq = 0) =>
217 call("read_session", { repo, number, viewer, afterSeq }),
218 };
219}
220
221export function billingClient(service: ServiceBinding): BillingApi {
222 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
223 return {
224 status: () => call("status", {}),
225 account: (workspace, viewer) => call("account", { workspace, viewer }),
226 ledger: (workspace, viewer) => call("ledger", { workspace, viewer }),
227 statement: (workspace, viewer, month = null, group = "day") => call("statement", { workspace, viewer, month, group }),
228 statementEntries: (workspace, viewer, filter) =>
229 call("statement_entries", {
230 workspace,
231 viewer,
232 month: filter.month,
233 kind: filter.kind,
234 day: filter.day ?? null,
235 project: filter.project ?? null,
236 before: filter.before ?? null,
237 }),
238 usage: (workspace, viewer, since) => call("usage", { workspace, viewer, since }),
239 checkout: (actor, workspace, amountCents, returnUrl) =>
240 call("checkout", { actor, workspace, amountCents, returnUrl }),
241 confirm: (workspace, viewer, session) => call("confirm", { workspace, viewer, session }),
242 canStart: (workspace) => call("can_start", { workspace }),
243 trial: (workspace, exempt) => call("trial", { workspace, exempt }),
244 startRun: (run) => call("start_run", run),
245 features: (workspace, viewer) => call("features", { workspace, viewer }),
246 subscribe: (actor, workspace, feature, returnUrl) =>
247 call("subscribe", { actor, workspace, feature, returnUrl }),
248 confirmSubscription: (workspace, viewer, session) =>
249 call("confirm_subscription", { workspace, viewer, session }),
250 cancelSubscription: (actor, workspace, feature, resume = false) =>
251 call("cancel_subscription", { actor, workspace, feature, resume }),
252 hasFeature: (workspace, feature) => call("has_feature", { workspace, feature }),
253 chargeFeature: (charge) => call("charge_feature", charge),
254 billingPortal: (actor, workspace, returnUrl) => call("billing_portal", { actor, workspace, return_url: returnUrl }),
255 recordSandbox: (usage) => call("record_sandbox", usage),
256 limit: (workspace, viewer) => call("limit", { workspace, viewer }),
257 checkLimit: (workspace) => call("check_limit", { workspace }),
258 prices: () => call("prices", {}),
259 notePending: (workspace, source, costMicros) => call("note_pending", { workspace, source, costMicros }),
260 setSpendLimit: (actor, workspace, spendLimitMicros, useFullLimit = false) =>
261 call("set_spend_limit", { actor, workspace, spendLimitMicros, use_full_limit: useFullLimit }),
262 invoices: (workspace, viewer) => call("invoices", { workspace, viewer }),
263 };
264}
265
266export function billingAdminClient(service: ServiceBinding): BillingAdminApi {
267 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
268 return {
269 accounts: (query) => call("admin_accounts", { query: query ?? null }),
270 account: (id) => call("admin_account", { id }),
271 setTerms: (id, terms, by) => call("admin_set_terms", { id, terms, by }),
272 createEnterprise: (name, workspaces, by) => call("admin_create_enterprise", { name, workspaces, by }),
273 attach: (workspace, account, by) => call("admin_attach", { workspace, account, by }),
274 credit: (workspace, amountMicros, note, by) => call("admin_credit", { workspace, amount_micros: amountMicros, note, by }),
275 billingLink: (workspace, by) => call("admin_billing_link", { workspace, by }),
276 stripe: (setup = false, by) => call("admin_stripe", { setup, by: by ?? null }),
277 enterpriseBilling: (id, email, by) => call("admin_enterprise_billing", { id, email, by }),
278 invoiceEnterprise: (id, by) => call("admin_invoice_enterprise", { id, by }),
279 accountsFor: (workspaces) => call("admin_accounts", { query: null, workspaces }),
280 signals: () => call("admin_signals", {}),
281 overview: () => call("admin_overview", {}),
282 sales: (workspace) => call("admin_sales", { workspace }),
283 setSales: (workspace, record, by) =>
284 call("admin_set_sales", {
285 workspace,
286 stage: record.stage,
287 owner: record.owner ?? null,
288 next_step: record.nextStep ?? null,
289 next_at: record.nextAt ?? null,
290 by,
291 }),
292 addNote: (workspace, text, by) => call("admin_add_note", { workspace, text, by }),
293 workspaceInvoices: (workspace) => call("admin_workspace_invoices", { workspace }),
294 allInvoices: (filter = {}) => call("admin_invoices", { status: filter.status ?? null, month: filter.month ?? null }),
295 audit: (filter = {}) =>
296 call("admin_audit", { by: filter.by ?? null, action: filter.action ?? null, before: filter.before ?? null }),
297 };
298}
299
300export function eventsClient(service: ServiceBinding): EventsApi {
301 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
302 return {
303 publish: (events) => call("publish", { events }),
304 list: (query) => call("list", query),
305 };
306}
307
308export function integrationsClient(service: ServiceBinding): IntegrationsApi {
309 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
310 return {
311 list: (workspace, viewer) => call("list", { workspace, viewer }),
312 connect: (actor, workspace, input) => call("connect", { actor, workspace, ...input }),
313 update: (actor, workspace, id, input) => call("update", { actor, workspace, id, ...input }),
314 disconnect: (actor, workspace, id) => call("disconnect", { actor, workspace, id }),
315 test: (actor, workspace, id) => call("test", { actor, workspace, id }),
316 deliveries: (workspace, viewer, id) => call("deliveries", { workspace, viewer, id }),
317 resolve: (workspace, viewer, reference) => call("resolve", { workspace, viewer, reference }),
318 references: (workspace, text, limit) => call("references", { workspace, text, limit }),
319 import: (actor, repo, reference, assign) => call("import", { actor, repo, reference, assign }),
320 links: (repo, number) => call("links", { repo, number }),
321 modelProvider: (workspace) => call("model_provider", { workspace }),
322 openModelSession: (run) => call("open_model_session", run),
323 modelUpstream: (token) => call("model_upstream", { token }),
324 routes: (workspace, viewer) => call("routes", { workspace, viewer }),
325 setRoutes: (actor, workspace, routes) => call("set_routes", { actor, workspace, routes }),
326 };
327}
328
329export function webhooksClient(service: ServiceBinding): WebhooksApi {
330 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
331 return {
332 list: (viewer, owner) => call("list", { viewer, ...owner }),
333 create: (actor, owner, input) => call("create", { actor, ...owner, ...input }),
334 update: (actor, owner, id, input) => call("update", { actor, ...owner, id, ...input }),
335 delete: (actor, owner, id) => call("delete", { actor, ...owner, id }),
336 ping: (actor, owner, id) => call("ping", { actor, ...owner, id }),
337 deliveries: (viewer, owner, id) => call("deliveries", { viewer, ...owner, id }),
338 redeliver: (actor, owner, deliveryId) => call("redeliver", { actor, ...owner, deliveryId }),
339 };
340}
341
342export function actionsClient(service: ServiceBinding): ActionsApi {
343 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
344 return {
345 workflows: (repo, viewer) => call("workflows", { repo, viewer }),
346 runs: (repo, viewer, filter = {}) => call("runs", { repo, viewer, ...filter }),
347 run: (repo, viewer, id) => call("run", { repo, viewer, id }),
348 logs: (repo, viewer, job, after = 0) => call("logs", { repo, viewer, job, after }),
349 dispatch: (actor, repo, workflow, ref, inputs) => call("dispatch", { actor, repo, workflow, ref, inputs }),
350 cancel: (actor, repo, id) => call("cancel", { actor, repo, id }),
351 rerun: (actor, repo, id, failedOnly = false) => call("rerun", { actor, repo, id, failed_only: failedOnly }),
352 setWorkflowEnabled: (actor, repo, workflow, enabled) =>
353 call("set_workflow_enabled", { actor, repo, workflow, enabled }),
354 settings: (actor, owner, kind) => call("settings", { actor, ...owner, kind }),
355 setSetting: (actor, owner, kind, name, value, options = {}) =>
356 call("set_setting", { actor, ...owner, kind, name, value, ...options }),
357 deleteSetting: (actor, owner, kind, name, id) => call("delete_setting", { actor, ...owner, kind, name, id }),
358 };
359}
360
361
362export function deploymentsClient(service: ServiceBinding): DeploymentsApi {
363 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
364 return {
365 settings: (project, viewer) => call("settings", { project, viewer }),
366 updateSettings: (actor, project, changes) => call("update_settings", { actor, project, changes }),
367 list: (project, viewer) => call("list", { project, viewer }),
368 get: (project, id, viewer) => call("get", { project, id, viewer }),
369 redeploy: (actor, project, branch) => call("redeploy", { actor, project, branch }),
370 takeDown: (actor, project, branch) => call("take_down", { actor, project, branch }),
371 stack: (actor, project, branch) => call("stack", { actor, project, branch }),
372 overview: (workspace, viewer) => call("overview", { workspace, viewer }),
373 usage: (workspace, viewer) => call("usage", { workspace, viewer }),
374 domains: (project, viewer) => call("domains", { project, viewer }),
375 addDomain: (actor, project, hostname, options = {}) =>
376 call("add_domain", { actor, project, hostname, twin: !!options.twin }),
377 removeDomain: (actor, project, id) => call("remove_domain", { actor, project, id }),
378 refreshDomain: (actor, project, id) => call("refresh_domain", { actor, project, id }),
379 };
380}
381
382export function projectsClient(service: ServiceBinding): ProjectsApi {
383 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
384 return {
385 list: (workspace, viewer) => call("list", { workspace, viewer }),
386 get: (workspace, slug, viewer) => call("get", { workspace, slug, viewer }),
387 byRepo: (repoId) => call("by_repo", { repoId }),
388 create: (actor, workspace, input) => call("create", { actor, workspace, input }),
389 update: (actor, workspace, slug, changes) => call("update", { actor, workspace, slug, changes }),
390 dependencies: (workspace, slug, viewer) => call("dependencies", { workspace, slug, viewer }),
391 addDependency: (actor, workspace, slug, on, as) => call("add_dependency", { actor, workspace, slug, on, as }),
392 removeDependency: (actor, workspace, slug, on) => call("remove_dependency", { actor, workspace, slug, on }),
393 graph: (projectId) => call("graph", { projectId }),
394 };
395}