@runlot/api 0.1.0-rc.16 → 0.1.0-rc.160

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,48 @@
1
1
  export const API_VERSION = "v1";
2
- /** 서버가 돌려준 오류 봉투를 그대로 들고 있는 예외. */
2
+ /** The shared query for browsing. Empty values are not carried — the server reads "empty means default". */
3
+ /** base64url of the UTF-8 JSON, no padding — the `draft` parameter's encoding. */
4
+ export function base64urlJson(v) {
5
+ const bytes = new TextEncoder().encode(JSON.stringify(v));
6
+ let bin = "";
7
+ for (const b of bytes)
8
+ bin += String.fromCharCode(b);
9
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
10
+ }
11
+ function gitQuery(ref, path) {
12
+ const q = new URLSearchParams();
13
+ if (ref !== "")
14
+ q.set("ref", ref);
15
+ if (path !== "")
16
+ q.set("path", path);
17
+ return q.size > 0 ? `?${q.toString()}` : "";
18
+ }
19
+ export const API_SCOPES = [
20
+ "project:read",
21
+ "deploy",
22
+ "db:read",
23
+ "db:write",
24
+ "repo:read",
25
+ "repo:write",
26
+ "org:admin",
27
+ ];
28
+ export const BUILTIN_AUTH_PROVIDERS = ["github", "google"];
29
+ export const RESERVED_AUTH_PROVIDER_IDS = ["github", "google", "runlot"];
30
+ /** The id pattern for an OIDC provider (`^[a-z][a-z0-9-]{1,30}$`). */
31
+ export const AUTH_PROVIDER_ID = /^[a-z][a-z0-9-]{1,30}$/;
32
+ export const AUTH_RUNLOT_METHODS = ["password", "google", "github", "passkey"];
33
+ /**
34
+ * A status the edge in front of cp-public can produce on its own: 502–504, and
35
+ * Cloudflare's 520–527 (524 is its 100 s origin timeout). With no JSON body these
36
+ * are the edge's words, not the server's, and are raised as `edge_<status>`.
37
+ */
38
+ export function isEdgeStatus(status) {
39
+ return (status >= 502 && status <= 504) || (status >= 520 && status <= 527);
40
+ }
41
+ /** True for the `edge_<status>` ApiError `isEdgeStatus` produces. */
42
+ export function isEdgeError(err) {
43
+ return err instanceof ApiError && err.code.startsWith("edge_");
44
+ }
45
+ /** The exception that carries the server's error envelope unchanged. */
3
46
  export class ApiError extends Error {
4
47
  status;
5
48
  code;
@@ -14,14 +57,25 @@ export class ApiError extends Error {
14
57
  }
15
58
  }
16
59
  /**
17
- * cp-public 클라이언트.
60
+ * The cp-public client.
18
61
  *
19
- * CLI와 대시보드가 같은 것을 쓴다. 각자 fetch를 부르면 오류 해석이 조금씩
20
- * 달라지고, 그 차이는 장애 중에 드러난다.
62
+ * The CLI and the dashboard use the same one. If each called fetch itself, their
63
+ * error handling would drift a little, and that difference shows up during an
64
+ * incident.
21
65
  */
22
66
  function dbPath(org, name) {
23
67
  return `/v1/orgs/${encodeURIComponent(org)}/projects/${encodeURIComponent(name)}/database`;
24
68
  }
69
+ function previewQuery(opts) {
70
+ const q = new URLSearchParams({ preview: opts.preview });
71
+ // Empty values are not carried: the server reads "absent" as its default, and
72
+ // `?db=` would be neither absent nor a member of the enum.
73
+ if (opts.db)
74
+ q.set("db", opts.db);
75
+ if (opts.from)
76
+ q.set("from", opts.from);
77
+ return q.toString();
78
+ }
25
79
  export class Client {
26
80
  opts;
27
81
  constructor(opts) {
@@ -45,8 +99,21 @@ export class Client {
45
99
  body = (await res.json());
46
100
  }
47
101
  catch {
48
- // 오류 응답이 JSON이 아닌 경우(프록시가 만든 502 등)도 같은 예외로
49
- // 올린다 — 호출부가 두 가지 실패 모양을 다루지 않게.
102
+ // An error response that is not JSON (a 502 made by a proxy, for instance)
103
+ // is raised as the same exception — so the caller does not have to handle
104
+ // two shapes of failure.
105
+ }
106
+ if (body === undefined && isEdgeStatus(res.status)) {
107
+ // The edge replaced the 5xx body with its own HTML. The code and reason
108
+ // the server wrote are not here — so say that, rather than "unknown". On
109
+ // 2026-09-10 a registrar rejection came out this way as
110
+ // "unknown: POST … → 502".
111
+ body = {
112
+ error: {
113
+ code: "edge_" + res.status,
114
+ message: "The server returned an error (" + res.status + "), and the error details could not be read. Try again shortly.",
115
+ },
116
+ };
50
117
  }
51
118
  throw new ApiError(res.status, body, `${method} ${path} → ${res.status}`);
52
119
  }
@@ -54,6 +121,21 @@ export class Client {
54
121
  return undefined;
55
122
  return (await res.json());
56
123
  }
124
+ /** A body that is not JSON (the raw mail). Error handling is the same as request. */
125
+ async text(method, path) {
126
+ const res = await fetch(new URL(path, this.opts.baseUrl), { method, headers: this.headers() });
127
+ if (!res.ok) {
128
+ let body;
129
+ try {
130
+ body = (await res.json());
131
+ }
132
+ catch {
133
+ // The same reason as in request
134
+ }
135
+ throw new ApiError(res.status, body, `${method} ${path} → ${res.status}`);
136
+ }
137
+ return await res.text();
138
+ }
57
139
  json(method, path, body) {
58
140
  if (body === undefined)
59
141
  return this.request(method, path);
@@ -65,38 +147,205 @@ export class Client {
65
147
  devLogin(subject) {
66
148
  return this.json("POST", "/v1/auth/dev/login", { subject });
67
149
  }
68
- /** 켜진 로그인 방식. 로그인 화면이 버튼을 그리는 데 쓴다. */
69
- authProviders() {
70
- return this.json("GET", "/v1/auth/providers");
150
+ /**
151
+ * Takes the sign-up and sends the confirmation mail. Neither a session nor a
152
+ * password is created here — the password is chosen in `verifyEmail` by
153
+ * whoever opens the mailbox.
154
+ */
155
+ passwordSignUp(email, name) {
156
+ return this.json("POST", "/v1/auth/password/sign-up", {
157
+ email,
158
+ ...(name === undefined ? {} : { name }),
159
+ });
160
+ }
161
+ passwordSignIn(email, password) {
162
+ return this.json("POST", "/v1/auth/password/sign-in", { email, password });
163
+ }
164
+ /** The same accepted response comes back whether or not the email exists. */
165
+ passwordForgot(email) {
166
+ return this.json("POST", "/v1/auth/password/forgot", { email });
167
+ }
168
+ passwordReset(token, password) {
169
+ return this.json("POST", "/v1/auth/password/reset", { token, password });
170
+ }
171
+ /** Uses the confirmation link and sets the account's first password. */
172
+ verifyEmail(token, password) {
173
+ return this.json("POST", "/v1/auth/email/verify", { token, password });
174
+ }
175
+ /**
176
+ * Finishes a sign-in that came back `{mfa:"totp"}`.
177
+ *
178
+ * Callable without a token: `pending` is the credential, and it is not a
179
+ * session — no other endpoint accepts it.
180
+ */
181
+ completeTotpLogin(pending, factor) {
182
+ return this.json("POST", "/v1/auth/totp", { pending, ...factor });
183
+ }
184
+ /** This account's two-factor state, including which orgs require it. */
185
+ getTotp() {
186
+ return this.json("GET", "/v1/me/totp");
187
+ }
188
+ /**
189
+ * Draws a secret to scan. It does **not** turn the factor on — `confirmTotp`
190
+ * does, after the app has proved it can produce a code.
191
+ */
192
+ enrollTotp() {
193
+ return this.json("POST", "/v1/me/totp/enroll");
194
+ }
195
+ /** Turns the factor on and hands back the ten recovery codes. They are shown once. */
196
+ confirmTotp(code) {
197
+ return this.json("POST", "/v1/me/totp/confirm", { code });
198
+ }
199
+ /** Turns it off. A code or a recovery code is required — the session alone is not. */
200
+ disableTotp(factor) {
201
+ return this.json("DELETE", "/v1/me/totp", factor);
71
202
  }
72
203
  /**
73
- * GitHub OAuth 시작 URL. 브라우저가 따라가는 302 라 fetch 로 부르지 않고
74
- * `window.location` 에 넣는다. `redirect` 는 서버 허용 목록에 있어야 한다.
204
+ * The GitHub OAuth start URL. It is a 302 the browser follows, so it goes into
205
+ * `window.location` rather than being called with fetch. `redirect` has to be
206
+ * on the server's allow-list.
75
207
  */
76
208
  githubStartUrl(redirect) {
77
209
  const u = new URL("/v1/auth/github/start", this.opts.baseUrl);
78
210
  u.searchParams.set("redirect", redirect);
79
211
  return u.toString();
80
212
  }
213
+ /** The Google OAuth start URL. Uses the same dashboard callback shape as GitHub. */
214
+ googleStartUrl(redirect) {
215
+ const u = new URL("/v1/auth/google/start", this.opts.baseUrl);
216
+ u.searchParams.set("redirect", redirect);
217
+ return u.toString();
218
+ }
219
+ /**
220
+ * The generic OIDC start URL (docs/onprem-delivery.md §7.7). Same 302-and-fragment
221
+ * shape as the other two; which provider is behind it is the installation's choice.
222
+ */
223
+ oidcStartUrl(redirect) {
224
+ const u = new URL("/v1/auth/oidc/start", this.opts.baseUrl);
225
+ u.searchParams.set("redirect", redirect);
226
+ return u.toString();
227
+ }
228
+ /**
229
+ * Does this deployment federate an identity provider?
230
+ *
231
+ * **There is no endpoint that answers "which logins are on"** — one existed and was
232
+ * deleted, because its only reader was the login screen and it put a round trip in
233
+ * front of every login button (cp/internal/public/public.go). This is not that
234
+ * endpoint coming back: cp-public **does not register** the two OIDC routes when no
235
+ * issuer is configured, so the mux's own 404 is the answer, and the probe is a HEAD
236
+ * that no handler runs.
237
+ *
238
+ * Any other status means the route is there — a 400 (this probe carries no
239
+ * `redirect`) or a 502 (the provider's discovery document could not be read) both say
240
+ * the handler exists, and a button that leads to a readable error beats no button.
241
+ * A network failure answers false: on SaaS, where the answer is false anyway, a dead
242
+ * API address must not draw a login that cannot work.
243
+ */
244
+ async oidcAvailable() {
245
+ try {
246
+ const res = await fetch(new URL("/v1/auth/oidc/start", this.opts.baseUrl), { method: "HEAD" });
247
+ return res.status !== 404;
248
+ }
249
+ catch {
250
+ return false;
251
+ }
252
+ }
253
+ /**
254
+ * This installation's licence (docs/onprem-delivery.md §6.5). Readable by any
255
+ * signed-in user: the footer it feeds is on every page for everybody.
256
+ *
257
+ * On SaaS it answers `onPrem: false` rather than 404, so the caller has one shape to
258
+ * read and the surfaces draw nothing on the flag.
259
+ */
260
+ license() {
261
+ return this.json("GET", "/v1/license");
262
+ }
263
+ /**
264
+ * The names of this deployment (app domain, docs address). Callable without auth.
265
+ *
266
+ * This exists so the dashboard does not hard-code a domain into the screen
267
+ * (docs/environments.md §3.2) — hard-coded, the dev screen tells people a
268
+ * production address, and because that address opens, nobody ever says it is
269
+ * wrong.
270
+ */
271
+ siteConfig() {
272
+ return this.json("GET", "/v1/config");
273
+ }
81
274
  me() {
82
275
  return this.json("GET", "/v1/me");
83
276
  }
84
277
  listOrgs() {
85
278
  return this.json("GET", "/v1/orgs");
86
279
  }
280
+ /** Changes the display name only (admin). The slug is the name that becomes an address, so it is not on this surface. */
281
+ /**
282
+ * `requireTotp` is left out when it is not given, on purpose: the server reads
283
+ * an absent field as "leave it alone". Sending `false` by default would mean a
284
+ * rename silently switched the org's second-factor requirement off.
285
+ */
286
+ updateOrg(org, name, requireTotp) {
287
+ return this.json("PATCH", `/v1/orgs/${encodeURIComponent(org)}`, {
288
+ name,
289
+ ...(requireTotp === undefined ? {} : { requireTotp }),
290
+ });
291
+ }
292
+ /**
293
+ * Deletes the organization (admin). **This cannot be undone.**
294
+ *
295
+ * `confirm` has to be the organization slug exactly — the confirmation lives on
296
+ * the server because three places call this surface (the screen, the CLI, and
297
+ * scripts). If a live project, domain, repository, or DNS zone is left, it is a
298
+ * 409 `org_not_empty` and `details.holdings` says what is left — **projects
299
+ * already deleted are not counted.**
300
+ *
301
+ * The `purgeAfter` in the answer is when the rows actually disappear. By the
302
+ * moment it returns the organization is already gone from every surface; what
303
+ * remains is retention until that time.
304
+ */
305
+ deleteOrg(org, confirm) {
306
+ return this.json("DELETE", `/v1/orgs/${encodeURIComponent(org)}`, { confirm });
307
+ }
87
308
  createOrg(slug, name) {
88
309
  return this.json("POST", "/v1/orgs", { slug, name });
89
310
  }
90
311
  /**
91
- * org 의 최근 알림 (docs/limits.md §3.4).
312
+ * The organization's recent notifications (docs/limits.md §3.4).
92
313
  *
93
- * `sentAt` 이 없는 행은 아직 큐에 있거나 받을 이메일이 없는 것이다 — 후자에게
94
- * 이 목록이 유일한 통로라, 화면은 두 상태를 같게 그린다.
314
+ * A row with no `sentAt` is either still queued or has no email address to
315
+ * reach — and for the second, this list is the only channel, so the screen
316
+ * draws both states the same way.
95
317
  */
96
318
  listNotifications(org, limit) {
97
319
  const q = limit === undefined ? "" : `?limit=${limit}`;
98
320
  return this.json("GET", `/v1/orgs/${encodeURIComponent(org)}/notifications${q}`);
99
321
  }
322
+ /**
323
+ * The plan and billing state (docs/billing.md). If `enabled` is false, this
324
+ * deployment has no billing — the screen shows only a contact address.
325
+ */
326
+ getBilling(org) {
327
+ return this.json("GET", `/v1/orgs/${encodeURIComponent(org)}/billing`);
328
+ }
329
+ /**
330
+ * A Pro checkout session. Send the browser to the `url` that comes back. Even
331
+ * once payment finishes, the thing that changes the plan is the webhook, so
332
+ * read `getBilling` again after the browser returns.
333
+ */
334
+ createBillingCheckout(org, returnTo) {
335
+ return this.json("POST", `/v1/orgs/${encodeURIComponent(org)}/billing/checkout`, { returnTo });
336
+ }
337
+ /** A one-time `url` for the customer portal (payment method, receipts, cancellation). */
338
+ createBillingPortal(org, returnTo) {
339
+ return this.json("POST", `/v1/orgs/${encodeURIComponent(org)}/billing/portal`, { returnTo });
340
+ }
341
+ /** The customer session token for the payment-method embed (1 hour). An org with no payment history gets a 404. */
342
+ createBillingSession(org) {
343
+ return this.json("POST", `/v1/orgs/${encodeURIComponent(org)}/billing/session`, {});
344
+ }
345
+ /** Schedules cancellation at the end of the period (`cancel: true`), or undoes it. There is no immediate revocation. */
346
+ cancelBilling(org, body) {
347
+ return this.json("POST", `/v1/orgs/${encodeURIComponent(org)}/billing/cancel`, body);
348
+ }
100
349
  listProjects(org) {
101
350
  return this.json("GET", `/v1/orgs/${encodeURIComponent(org)}/projects`);
102
351
  }
@@ -106,17 +355,231 @@ export class Client {
106
355
  getProject(org, name) {
107
356
  return this.json("GET", `/v1/orgs/${encodeURIComponent(org)}/projects/${encodeURIComponent(name)}`);
108
357
  }
358
+ /**
359
+ * Renames the project (admin). **The default address moves with it and there is
360
+ * no alias** — which is why the response carries the new address. Unlike the
361
+ * org slug, this name can change because it is the inner label of the org
362
+ * wildcard certificate.
363
+ */
364
+ updateProject(org, name, next) {
365
+ return this.json("PATCH", this.projectPath(org, name), { name: next });
366
+ }
367
+ /**
368
+ * Starts tearing the project down (admin). **This cannot be undone and leaves
369
+ * no recovery generation.** `confirm` has to be the project name exactly.
370
+ */
371
+ deleteProject(org, name, confirm) {
372
+ return this.json("DELETE", this.projectPath(org, name), { confirm });
373
+ }
374
+ /**
375
+ * Disables a project (admin): it stops serving and taking new backups, and
376
+ * keeps everything it has. A project disabled for a year is deleted for good.
377
+ */
378
+ disableProject(org, name) {
379
+ return this.json("POST", `${this.projectPath(org, name)}/disable`);
380
+ }
381
+ /** Enables a disabled project (admin). 409 `project_limit` when there is no room for it. */
382
+ enableProject(org, name) {
383
+ return this.json("POST", `${this.projectPath(org, name)}/enable`);
384
+ }
385
+ /** Watches the teardown operation to its end even after the project is gone. */
386
+ getOrgOperation(org, opId) {
387
+ return this.json("GET", `/v1/orgs/${encodeURIComponent(org)}/operations/${encodeURIComponent(opId)}`);
388
+ }
389
+ /** Everything the project's first screen takes in one call. Usage calls `getUsage` alongside it. */
390
+ getProjectOverview(org, name) {
391
+ return this.json("GET", `${this.projectPath(org, name)}/overview`);
392
+ }
109
393
  listDeployments(org, name) {
110
394
  return this.json("GET", `/v1/orgs/${encodeURIComponent(org)}/projects/${encodeURIComponent(name)}/deployments`);
111
395
  }
112
- /** 본문이 곧 번들이다. 다이제스트 하나가 코드와 자산 전부를 덮는다. */
113
- deploy(org, name, bundle) {
396
+ /**
397
+ * One deployment, with `migrations` when the control plane applied its
398
+ * `migrations/` — which today means a preview deployed with `db=branch`
399
+ * (docs/studio.md §6.6 step 2).
400
+ *
401
+ * A preview's deployment is read under **the parent project's name**, the name
402
+ * the caller deployed through: the preview is a project of its own, but the
403
+ * caller never learns its name.
404
+ */
405
+ getDeployment(org, name, deploymentId) {
406
+ return this.json("GET", `${this.projectPath(org, name)}/deployments/${encodeURIComponent(deploymentId)}`);
407
+ }
408
+ /**
409
+ * Scheduled runs: what the live deployment declares, when each fires next, and
410
+ * the recent history (docs/cron.md §8). `limit` bounds the history rows only —
411
+ * the schedules and the per-schedule last run are never paged.
412
+ */
413
+ getProjectCron(org, name, limit) {
414
+ const qs = limit ? `?limit=${limit}` : "";
415
+ return this.json("GET", `${this.projectPath(org, name)}/cron${qs}`);
416
+ }
417
+ /**
418
+ * Queues: what the live deployment declares, how deep each one is, and the
419
+ * recent batch history (docs/queues.md §6). The depth is read from the
420
+ * project's own database; `depthError` on the answer says when it could not be.
421
+ */
422
+ getProjectQueues(org, name, limit) {
423
+ const qs = limit ? `?limit=${limit}` : "";
424
+ return this.json("GET", `${this.projectPath(org, name)}/queues${qs}`);
425
+ }
426
+ /**
427
+ * Durable Objects: how many this project has placed, against the two caps
428
+ * (docs/durable-objects.md).
429
+ *
430
+ * **It answers how much, never which.** There is no actor id in the response
431
+ * and none is coming — those name individual objects, and a list of them would
432
+ * be an object enumeration wearing a quota's name. `nodes` is keyed by node id
433
+ * because `nodeLimit` is a separate bound that can refuse a placement while
434
+ * the project-wide cap still has room.
435
+ */
436
+ getProjectDurableObjects(org, name) {
437
+ return this.json("GET", `${this.projectPath(org, name)}/durable-objects`);
438
+ }
439
+ queuePath(org, name, queue) {
440
+ return `${this.projectPath(org, name)}/queues/${encodeURIComponent(queue)}`;
441
+ }
442
+ listQueueRuns(org, name, queue, limit) {
443
+ const qs = limit ? `?limit=${limit}` : "";
444
+ return this.json("GET", `${this.queuePath(org, name, queue)}/runs${qs}`);
445
+ }
446
+ /** The head of the queue without leasing it — looking cannot delay a delivery. */
447
+ peekQueue(org, name, queue, limit) {
448
+ const qs = limit ? `?limit=${limit}` : "";
449
+ return this.json("GET", `${this.queuePath(org, name, queue)}/messages${qs}`);
450
+ }
451
+ /** Irreversible. The confirmation is the caller's — the server holds none. */
452
+ purgeQueue(org, name, queue) {
453
+ return this.json("DELETE", `${this.queuePath(org, name, queue)}/messages`);
454
+ }
455
+ /**
456
+ * Moves a dead-letter queue's messages back. `to` is required only when the
457
+ * dead-letter queue belongs to more than one consumer, or to none.
458
+ */
459
+ redriveQueue(org, name, queue, to) {
460
+ return this.json("POST", `${this.queuePath(org, name, queue)}/redrive`, to === undefined ? {} : { to });
461
+ }
462
+ /**
463
+ * The vector store: every namespace with its count and width, and the plan's
464
+ * bounds (docs/vectors.md §4). Read from the project's own database;
465
+ * `readError` on the answer says when it could not be.
466
+ */
467
+ getProjectVectors(org, name) {
468
+ return this.json("GET", `${this.projectPath(org, name)}/vectors`);
469
+ }
470
+ /** Irreversible. The confirmation is the caller's — the server holds none. */
471
+ deleteVectorNamespace(org, name, namespace) {
472
+ return this.json("DELETE", `${this.projectPath(org, name)}/vectors/${encodeURIComponent(namespace)}`);
473
+ }
474
+ /** The body is the bundle. One digest covers all of the code and the assets. */
475
+ /**
476
+ * Uploads the bundle. `headers` carries the provenance headers
477
+ * (`X-Runlot-Git-*`, openapi createDeployment) — the body is the bundle
478
+ * itself, so the metadata can only travel in headers.
479
+ */
480
+ deploy(org, name, bundle, headers = {}) {
114
481
  return this.request("POST", `/v1/orgs/${encodeURIComponent(org)}/projects/${encodeURIComponent(name)}/deployments`, {
115
482
  body: bundle,
483
+ headers: { ...headers, "Content-Type": "application/gzip" },
484
+ });
485
+ }
486
+ /**
487
+ * The same upload, aimed at a preview (docs/preview.md). **It does not move
488
+ * production's live pointer** — that is the whole difference, and it is why
489
+ * this is a named method rather than an optional argument on `deploy`: a
490
+ * caller that forgets the argument deploys to production.
491
+ *
492
+ * `db` picks what `env.db` points at (`branch` by default, `shared` at
493
+ * production's own database, `none` for no database), and `from` pours the
494
+ * branch from a named generation instead of the newest one.
495
+ */
496
+ deployPreview(org, name, bundle,
497
+ // `| undefined` spelled out: under exactOptionalPropertyTypes a caller that
498
+ // forwards an unset flag is passing the property, not omitting it.
499
+ opts, headers = {}) {
500
+ return this.request("POST", `${this.projectPath(org, name)}/deployments?${previewQuery(opts)}`, {
501
+ body: bundle,
502
+ headers: { ...headers, "Content-Type": "application/gzip" },
503
+ });
504
+ }
505
+ /**
506
+ * Opens an incremental upload (docs/incremental-deploy-upload.md §1.1). `files` is
507
+ * the bundle's entry list in tar order; the answer names the hashes to upload.
508
+ * An older CP answers 404 here — the caller falls back to `deploy`.
509
+ */
510
+ createDeploymentUpload(org, name, files, preview) {
511
+ let path = `${this.projectPath(org, name)}/deployments/uploads`;
512
+ if (preview)
513
+ path += `?${previewQuery(preview)}`;
514
+ return this.json("POST", path, { files });
515
+ }
516
+ /** One batch: a gzip tar whose entries are named by their content's sha256 (§1.2). */
517
+ uploadDeploymentBlobs(org, name, uploadId, batch) {
518
+ return this.request("POST", `${this.projectPath(org, name)}/deployments/uploads/${encodeURIComponent(uploadId)}/blobs`, {
519
+ body: batch,
116
520
  headers: { "Content-Type": "application/gzip" },
117
521
  });
118
522
  }
119
- /** 멱등이다. 두 번 불러도 비밀번호는 굴지 않고 같은 접속 정보가 온다. */
523
+ /**
524
+ * Assembles and deploys the session (§1.3). The answer is `createDeployment`'s
525
+ * (with `preview` for a preview session). Idempotent per session, so a retry
526
+ * after an edge timeout returns the same deployment.
527
+ */
528
+ commitDeploymentUpload(org, name, uploadId, headers = {}) {
529
+ return this.request("POST", `${this.projectPath(org, name)}/deployments/uploads/${encodeURIComponent(uploadId)}/commit`, {
530
+ headers,
531
+ });
532
+ }
533
+ /** The parent's live previews (viewer). A deleted preview is not listed. */
534
+ listPreviews(org, name) {
535
+ return this.json("GET", `${this.projectPath(org, name)}/previews`);
536
+ }
537
+ /**
538
+ * Deletes a preview and its branch (member).
539
+ *
540
+ * No confirmation string, unlike `deleteProject`: a branch is a copy taken at a
541
+ * moment and nothing in it is the only copy of anything.
542
+ */
543
+ deletePreview(org, name, preview) {
544
+ return this.json("DELETE", `${this.projectPath(org, name)}/previews/${encodeURIComponent(preview)}`);
545
+ }
546
+ /**
547
+ * Makes the preview's artifact the parent's live deployment (member).
548
+ *
549
+ * **The code, never the data** (docs/preview.md §7). The branch is not merged
550
+ * and production's database is not replaced. The preview stays alive.
551
+ */
552
+ promotePreview(org, name, preview) {
553
+ return this.json("POST", `${this.projectPath(org, name)}/previews/${encodeURIComponent(preview)}/promote`);
554
+ }
555
+ /**
556
+ * The project's share link — `<label>.share.<app-domain>`, the one address
557
+ * Studio hands to somebody who is not a developer (docs/studio.md §6.9).
558
+ *
559
+ * 404 when the project has never been shared: a link is minted by
560
+ * `putShareLink`, never as a side effect of reading.
561
+ */
562
+ getShareLink(org, name) {
563
+ return this.json("GET", `${this.projectPath(org, name)}/share`);
564
+ }
565
+ /**
566
+ * Points the share link at a preview, minting the label if there is none.
567
+ *
568
+ * Idempotent: the label is kept across shares, so somebody holding the link
569
+ * keeps working. `rotate` mints a new label and retires the old name in the
570
+ * same request ("링크 재발급"), so the project never has two live links.
571
+ */
572
+ putShareLink(org, name, opts = {}) {
573
+ return this.json("PUT", `${this.projectPath(org, name)}/share`, {
574
+ ...(opts.preview === undefined ? {} : { preview: opts.preview }),
575
+ ...(opts.rotate === undefined ? {} : { rotate: opts.rotate }),
576
+ });
577
+ }
578
+ /** Stops the link answering and forgets the label. The preview keeps running. */
579
+ deleteShareLink(org, name) {
580
+ return this.json("DELETE", `${this.projectPath(org, name)}/share`);
581
+ }
582
+ /** Idempotent. Called twice, the password is not rolled and the same connection details come back. */
120
583
  createDatabase(org, name) {
121
584
  return this.json("POST", `/v1/orgs/${encodeURIComponent(org)}/projects/${encodeURIComponent(name)}/database`);
122
585
  }
@@ -124,17 +587,18 @@ export class Client {
124
587
  return this.json("GET", `/v1/orgs/${encodeURIComponent(org)}/projects/${encodeURIComponent(name)}/database`);
125
588
  }
126
589
  /**
127
- * 접속 자격까지. `getDatabase` 와 라우트가 갈린 것은 역할 때문이다 —
128
- * viewer 는 여부를 알아도 되지만 비밀번호는 아니다 (proto/openapi.yaml).
590
+ * The connection credentials as well. The route is split from `getDatabase`
591
+ * because of roles — a viewer may know whether there is a database, but not
592
+ * the password (proto/openapi.yaml).
129
593
  */
130
594
  getDatabaseConnect(org, name) {
131
595
  return this.json("GET", `/v1/orgs/${encodeURIComponent(org)}/projects/${encodeURIComponent(name)}/database/connect`);
132
596
  }
133
- /** 접속 끝점만 — 자격 없음. viewer 도 받는다. `runlot port-forward` 가 쓴다. */
597
+ /** The endpoint only — no credentials. A viewer gets it too. Used by `runlot port-forward`. */
134
598
  getDatabaseEndpoint(org, name) {
135
599
  return this.json("GET", `${dbPath(org, name)}/endpoint`);
136
600
  }
137
- /** 단기 기계 자격 발급. 비밀번호는 이 응답에만 실린다. */
601
+ /** Issues a short-lived machine credential. The password is carried in this response and nowhere else. */
138
602
  createDatabaseToken(org, name, ttlSeconds) {
139
603
  return this.json("POST", `${dbPath(org, name)}/tokens`, ttlSeconds === undefined ? {} : { ttlSeconds });
140
604
  }
@@ -145,52 +609,84 @@ export class Client {
145
609
  return this.json("DELETE", `${dbPath(org, name)}/tokens/${encodeURIComponent(user)}`);
146
610
  }
147
611
  /**
148
- * 진단 이미지를 하나 만든다.
612
+ * Makes one diagnostic image.
149
613
  *
150
- * **멱등이 아니다** — 부를 때마다 이미지가 하나 생긴다. 그리고 느리다:
151
- * 응답은 덤프가 끝난 뒤에 오고, 그동안 그 프로젝트의 액터는 붙잡혀 있다
152
- * (proto/openapi.yaml).
614
+ * **Not idempotent** — every call makes another image. And it is slow: the
615
+ * response comes after the dump finishes, and that project's actor is held
616
+ * for the whole of it (proto/openapi.yaml).
153
617
  */
154
618
  exportDatabase(org, name) {
155
619
  return this.json("POST", `/v1/orgs/${encodeURIComponent(org)}/projects/${encodeURIComponent(name)}/database/export`);
156
620
  }
157
621
  /**
158
- * 복원이 고를 수 있는 세대 전부. 최신 순이고, `lastCheckedAt` 은 무변경
159
- * 스킵의 하트비트다 — 세대가 늘지 않는 것과 백업이 죽은 것을 가른다.
622
+ * Every generation a restore can choose, newest first. `lastCheckedAt` is the
623
+ * heartbeat of the no-change skip — it is what tells "no new generations"
624
+ * apart from "the backup is dead".
160
625
  */
161
626
  listGenerations(org, name) {
162
627
  return this.json("GET", `${this.dbPath(org, name)}/generations`);
163
628
  }
164
629
  /**
165
- * 세대로 되돌린다. **그 사이의 쓰기는 사라진다.**
630
+ * Runs one statement in the project's database (the dashboard console).
631
+ *
632
+ * `readOnly` is **omitted, not sent as false**, when the caller wants the safe
633
+ * mode: the server treats an absent field as read-only, so leaving it out is the
634
+ * one spelling that cannot be misread. Sending `false` is the explicit ask for
635
+ * write mode, and only then does the server run outside a transaction.
636
+ *
637
+ * SQL failures arrive as an `ApiError` whose body carries `details.sqlstate` —
638
+ * PostgreSQL's own code, which is what the error panel shows.
639
+ */
640
+ executeSQL(org, name, sql, opts = {}) {
641
+ const body = { sql };
642
+ if (opts.readOnly === false)
643
+ body.readOnly = false;
644
+ if (opts.params !== undefined && opts.params.length > 0)
645
+ body.params = opts.params;
646
+ return this.json("POST", `${this.dbPath(org, name)}/execute`, body);
647
+ }
648
+ /**
649
+ * Rolls back to a generation. **Writes made since then are lost.**
166
650
  *
167
- * 202 로 끝난다 — 돌아오는 것은 연산 id 이고, 진행은
168
- * `getDatabaseOperation` 으로 본다. `latest` 는 서버가 풀지 않는다:
169
- * 목록에서 고른 `(epoch, seq)` 를 그대로 싣는다 (proto/openapi.yaml).
651
+ * It ends at 202 — what comes back is an operation id, and progress is read
652
+ * through `getDatabaseOperation`. The server does not resolve `latest`: the
653
+ * `(epoch, seq)` chosen from the list is carried as-is (proto/openapi.yaml).
170
654
  */
171
655
  restoreDatabase(org, name, epoch, seq) {
172
656
  return this.json("POST", `${this.dbPath(org, name)}/restore`, { epoch, seq });
173
657
  }
174
658
  /**
175
- * 데이터베이스를 없앤다. `confirm` 은 프로젝트 이름과 **정확히** 같아야
176
- * 하고, 다르면 서버가 400 `confirm_mismatch` 로 거절한다.
659
+ * Rolls back to a restore point **inside** a backup (pg-feather docs/37):
660
+ * `txnId` is that commit, `at` is the last commit at or before that time. One
661
+ * backup carries the commits in between in order, so the place you can roll
662
+ * back to is not tied to a backup boundary. Everything else is as in
663
+ * restoreDatabase — 202, an operation id, and one safety backup before the
664
+ * rollback.
665
+ */
666
+ restoreDatabaseTo(org, name, target) {
667
+ return this.json("POST", `${this.dbPath(org, name)}/restore`, target);
668
+ }
669
+ /**
670
+ * Removes the database. `confirm` has to match the project name **exactly**;
671
+ * if it does not, the server refuses with 400 `confirm_mismatch`.
177
672
  */
178
673
  deleteDatabase(org, name, confirm) {
179
674
  return this.json("POST", `${this.dbPath(org, name)}/delete`, { confirm });
180
675
  }
181
- /** 연산 하나의 진행. 연산 id 는 자격이 아니라 프로젝트 경로 아래에 있다. */
676
+ /** The progress of one operation. The operation id is not a credential; it lives under the project path. */
182
677
  getDatabaseOperation(org, name, opId) {
183
678
  return this.json("GET", `${this.dbPath(org, name)}/operations/${encodeURIComponent(opId)}`);
184
679
  }
185
- /** 되돌릴 수 없는 phase 앞의 연산을 중단한다. */
680
+ /** Aborts an operation that has not yet reached a phase it cannot come back from. */
186
681
  abortDatabaseOperation(org, name, opId) {
187
682
  return this.json("POST", `${this.dbPath(org, name)}/operations/${encodeURIComponent(opId)}/abort`);
188
683
  }
189
684
  // ---- Phase 6 (docs/phase6.md) ----
190
685
  /**
191
- * 로그 라이브 테일. **JSON 이 아니라 스트림**이라 `request` 를 안 지난다 —
192
- * 돌려주는 것은 줄 단위 `LogEvent` 의 async iterable 이고, `signal` 을 abort
193
- * 하면 연결이 끊긴다. 오류 응답(4xx/5xx)은 다른 메서드와 같은 `ApiError` 다.
686
+ * A live tail of the logs. It is **a stream, not JSON**, so it does not go
687
+ * through `request` — what comes back is an async iterable of line-by-line
688
+ * `LogEvent`, and aborting `signal` closes the connection. An error response
689
+ * (4xx/5xx) is the same `ApiError` as in every other method.
194
690
  */
195
691
  async *tailLogs(org, name, opts = {}) {
196
692
  const q = new URLSearchParams();
@@ -210,7 +706,7 @@ export class Client {
210
706
  body = (await res.json());
211
707
  }
212
708
  catch {
213
- // 위의 request 와 같은 이유.
709
+ // The same reason as in request above.
214
710
  }
215
711
  throw new ApiError(res.status, body, `GET ${path} → ${res.status}`);
216
712
  }
@@ -238,14 +734,35 @@ export class Client {
238
734
  yield JSON.parse(rest);
239
735
  }
240
736
  finally {
241
- // 소비자가 일찍 끝내면(break) 서버 쪽 follow 도 끝나야 한다.
737
+ // If the consumer ends early (break), the server's follow has to end too.
242
738
  await reader.cancel().catch(() => { });
243
739
  }
244
740
  }
741
+ /**
742
+ * The stored lane (0062). It is a plain JSON page, not a stream: the history
743
+ * does not reach a node, so it answers for a project that is cold, parked, or
744
+ * has moved since the lines were written — every one of which is a 409 on
745
+ * `tailLogs`.
746
+ *
747
+ * `q` is a plain substring, matched case-insensitively. It is not a regular
748
+ * expression — `%` and `_` match themselves.
749
+ *
750
+ * Paging is keyset: pass the `cursor` from a page back to get the next, older
751
+ * one. A page with no `cursor` is the end of what is kept.
752
+ */
753
+ getLogHistory(org, name, opts = {}) {
754
+ const params = new URLSearchParams();
755
+ for (const [k, v] of Object.entries(opts)) {
756
+ if (v !== undefined && v !== "")
757
+ params.set(k, String(v));
758
+ }
759
+ const qs = params.size ? `?${params}` : "";
760
+ return this.json("GET", `${this.projectPath(org, name)}/logs/history${qs}`);
761
+ }
245
762
  listSecrets(org, name) {
246
763
  return this.json("GET", `${this.projectPath(org, name)}/secrets`);
247
764
  }
248
- /** 값은 이 호출로만 나간다. 어떤 응답에도 값은 없다. */
765
+ /** The value travels in this call only. It is in no response at all. */
249
766
  setSecret(org, name, secret, value) {
250
767
  return this.json("PUT", `${this.projectPath(org, name)}/secrets/${encodeURIComponent(secret)}`, { value });
251
768
  }
@@ -256,111 +773,339 @@ export class Client {
256
773
  const q = hours === undefined ? "" : `?hours=${hours}`;
257
774
  return this.json("GET", `${this.projectPath(org, name)}/usage${q}`);
258
775
  }
259
- // ---- 오브젝트 스토리지 (docs/storage.md §8) ----
260
- /** 부여 여부·접두·쿼터·사용량. `usedBytes` 는 노드 보고 주기만큼 늦다. */
776
+ // ---- Object storage (docs/storage.md §8) ----
777
+ /** Grant, prefix, quota, usage. `usedBytes` lags by the node's reporting interval. */
261
778
  getStorage(org, name) {
262
779
  return this.json("GET", `${this.projectPath(org, name)}/storage`);
263
780
  }
264
781
  /**
265
- * 스토리지를 부여한다. 멱등이라 두 번 눌러도 접두는 그대로다. 접두·쿼터를
266
- * 인자로 받지 않는 것이 요점이다 — 접두는 격리의 경계이고 쿼터는 요금제가
267
- * 정한다 (proto/openapi.yaml).
782
+ * Grants storage. It is idempotent, so pressing twice leaves the prefix as it
783
+ * was. Taking neither the prefix nor the quota as an argument is the point —
784
+ * the prefix is the isolation boundary and the quota is set by the plan
785
+ * (proto/openapi.yaml).
268
786
  */
269
787
  grantStorage(org, name) {
270
788
  return this.json("POST", `${this.projectPath(org, name)}/storage`);
271
789
  }
272
- /** 부여를 뗀다. **객체는 지워지지 않는다** (docs/storage.md §7). */
790
+ /** Removes the grant. **The objects are not deleted** (docs/storage.md §7). */
273
791
  revokeStorage(org, name) {
274
792
  return this.json("DELETE", `${this.projectPath(org, name)}/storage`);
275
793
  }
276
- // ---- 최종 사용자 인증 (docs/auth.md §9) ----
277
794
  /**
278
- * 부여 여부·설정·프로바이더·호스트. **가입자는 안 온다** — 그 표는 프로젝트
279
- * DB 안이고 (docs/auth.md §6) 워커의 `env.auth` 만 본다.
795
+ * The key prefixes this project serves unsigned (docs/storage.md §4.7).
280
796
  *
281
- * `providers` 에는 client id 만 있다. 클라이언트 시크릿은 봉인돼 어느
282
- * 응답에도 안 나온다.
797
+ * A prefix is stored normalized — `assets` becomes `assets/`, and `/` becomes
798
+ * the empty string, which means every key. The value that comes back is the
799
+ * value that governs, so a screen must render the response rather than what
800
+ * the user typed.
801
+ */
802
+ listStoragePublic(org, name) {
803
+ return this.json("GET", `${this.projectPath(org, name)}/storage/public`);
804
+ }
805
+ /** Publishes a prefix. Idempotent. All three verbs answer with the whole list. */
806
+ addStoragePublic(org, name, prefix) {
807
+ return this.json("POST", `${this.projectPath(org, name)}/storage/public`, { prefix });
808
+ }
809
+ /**
810
+ * Unpublishes a prefix. Idempotent.
811
+ *
812
+ * **The world keeps reading for up to a minute.** The object front caches the
813
+ * list, so this call is not a revocation that takes effect at the instant it
814
+ * returns — a screen that says "no longer public" the moment this resolves is
815
+ * telling a small lie.
816
+ */
817
+ removeStoragePublic(org, name, prefix) {
818
+ return this.json("DELETE", `${this.projectPath(org, name)}/storage/public`, { prefix });
819
+ }
820
+ // ---- Email (docs/email.md §5) ----
821
+ /** Grant, address, sender, limits, recent counts. The address comes back as a preview even without a grant. */
822
+ getEmail(org, name) {
823
+ return this.json("GET", `${this.projectPath(org, name)}/email`);
824
+ }
825
+ /** Turns it on. **Idempotent** — we choose the address. The deploy reads `"email": true` and calls this. */
826
+ grantEmail(org, name) {
827
+ return this.json("POST", `${this.projectPath(org, name)}/email`);
828
+ }
829
+ /** Turns it off. Mail arriving at that address now gets a 550. */
830
+ revokeEmail(org, name) {
831
+ return this.json("DELETE", `${this.projectPath(org, name)}/email`);
832
+ }
833
+ // ---- Custom sending domains (docs/email.md §2.4) ----
834
+ /** The project's own sending domains, each with the records to publish. */
835
+ listEmailDomains(org, name) {
836
+ return this.json("GET", `${this.projectPath(org, name)}/email/domains`);
837
+ }
838
+ /**
839
+ * Creates the provider identity and answers with the records to publish.
840
+ * `publish` writes them into the zone when we host one covering the domain.
841
+ */
842
+ addEmailDomain(org, name, domain, publish = false) {
843
+ return this.json("POST", `${this.projectPath(org, name)}/email/domains`, { domain, publish });
844
+ }
845
+ /** Re-checks now. The background loop does the same once a minute while pending. */
846
+ verifyEmailDomain(org, name, domain) {
847
+ return this.json("POST", `${this.projectPath(org, name)}/email/domains/${encodeURIComponent(domain)}/verify`);
848
+ }
849
+ /** Deletes the identity and the row. Sending from it is refused from the next convergence. */
850
+ removeEmailDomain(org, name, domain) {
851
+ return this.json("DELETE", `${this.projectPath(org, name)}/email/domains/${encodeURIComponent(domain)}`);
852
+ }
853
+ // ---- AI (docs/ai.md §6) ----
854
+ /**
855
+ * The model catalogue. **Being logged in is enough to see it** — what you can
856
+ * buy is not an organization's secret, and this list is the price table.
857
+ *
858
+ * Prices are integer **micro-cents** per million tokens (1 µ¢ = 1e-8 USD).
859
+ * Not letting the server pick the decimal place is the point — a small call
860
+ * rounded to cents becomes 0.
861
+ */
862
+ listAIModels() {
863
+ return this.json("GET", "/v1/ai/models");
864
+ }
865
+ /** Grant, limits, the org balance, 24 h usage. The limits come back as a preview even without a grant. */
866
+ getAI(org, name) {
867
+ return this.json("GET", `${this.projectPath(org, name)}/ai`);
868
+ }
869
+ /** Turns it on. **Idempotent.** The deploy reads `"ai": true` and calls this. */
870
+ grantAI(org, name) {
871
+ return this.json("POST", `${this.projectPath(org, name)}/ai`);
872
+ }
873
+ /**
874
+ * Lends the org's own Claude/Codex subscriptions to this project's
875
+ * `anthropic/*` and `openai/*` calls (docs/studio-byos-ai.md §3.1).
876
+ *
877
+ * **Omitting a field leaves it as it was**, so turning lending on does not
878
+ * clear a fallback that was already set. Admin only: the subscription that
879
+ * carries the vendor-terms risk belongs to a person, not to the org.
880
+ */
881
+ patchAI(org, name, body) {
882
+ return this.json("PATCH", `${this.projectPath(org, name)}/ai`, body);
883
+ }
884
+ /** Turns it off. **The ledger and the balance are untouched** — the balance belongs to the org and the grant belongs to the project. */
885
+ revokeAI(org, name) {
886
+ return this.json("DELETE", `${this.projectPath(org, name)}/ai`);
887
+ }
888
+ /** The org's credit balance and its automatic top-up settings. The balance is in micro-cents and can be negative. */
889
+ getAICredit(org) {
890
+ return this.json("GET", `/v1/orgs/${encodeURIComponent(org)}/ai/credit`);
891
+ }
892
+ /** One page of the org ledger. The cursor is `ledger_id` — cutting on time splits the same millisecond. */
893
+ listAILedger(org, opts = {}) {
894
+ const q = new URLSearchParams();
895
+ if (opts.limit)
896
+ q.set("limit", String(opts.limit));
897
+ if (opts.before)
898
+ q.set("before", String(opts.before));
899
+ const qs = q.toString();
900
+ return this.json("GET", `/v1/orgs/${encodeURIComponent(org)}/ai/ledger${qs ? "?" + qs : ""}`);
901
+ }
902
+ /**
903
+ * The credit top-up checkout. **A browser coming back is not evidence** — the
904
+ * one thing that raises the balance is the `order.paid` webhook, and the
905
+ * screen polls the balance after the success event.
906
+ */
907
+ createAICreditCheckout(org, microCents, returnTo) {
908
+ return this.json("POST", `/v1/orgs/${encodeURIComponent(org)}/ai/credit/checkout`, { microCents, returnTo });
909
+ }
910
+ /**
911
+ * Turns automatic top-up on or off. **Turning it on is explicit consent**
912
+ * (docs/ai.md §3.5) — the screen shows the charging terms verbatim and calls
913
+ * this only after the box is checked.
914
+ */
915
+ setAIAutoTopup(org, body) {
916
+ return this.json("PUT", `/v1/orgs/${encodeURIComponent(org)}/ai/autotopup`, body);
917
+ }
918
+ /** One page of the mail log (docs/email.md §6.1). Newest first, cursor-paged. */
919
+ listMailLog(org, name, opts = {}) {
920
+ const q = new URLSearchParams();
921
+ if (opts.direction)
922
+ q.set("direction", opts.direction);
923
+ if (opts.cursor)
924
+ q.set("cursor", opts.cursor);
925
+ if (opts.limit)
926
+ q.set("limit", String(opts.limit));
927
+ const qs = q.toString();
928
+ return this.json("GET", `${this.projectPath(org, name)}/email/log${qs ? "?" + qs : ""}`);
929
+ }
930
+ /** The metadata of one message. */
931
+ getMailLog(org, name, mailId) {
932
+ return this.json("GET", `${this.projectPath(org, name)}/email/log/${encodeURIComponent(mailId)}`);
933
+ }
934
+ /** The URL of the raw message — the screen uses it as a download link (.eml). */
935
+ mailLogRawURL(org, name, mailId) {
936
+ return new URL(`${this.projectPath(org, name)}/email/log/${encodeURIComponent(mailId)}/raw`, this.opts.baseUrl).toString();
937
+ }
938
+ /** The raw text. What the detail view draws the headers and body from. */
939
+ getMailLogRaw(org, name, mailId) {
940
+ return this.text("GET", `${this.projectPath(org, name)}/email/log/${encodeURIComponent(mailId)}/raw`);
941
+ }
942
+ // ---- End-user authentication (docs/auth.md §9) ----
943
+ /**
944
+ * Grant, settings, providers, hosts. **The signed-up users do not come** —
945
+ * that table is inside the project DB (docs/auth.md §6) and only the worker's
946
+ * `env.auth` sees it.
947
+ *
948
+ * `providers` carries the client id only. The client secret is sealed and
949
+ * appears in no response.
283
950
  */
284
951
  getAuth(org, name) {
285
952
  return this.json("GET", `${this.projectPath(org, name)}/auth`);
286
953
  }
287
954
  /**
288
- * 인증을 켠다 (member). 멱등이다.
955
+ * Turns auth on (member). Idempotent.
289
956
  *
290
- * **데이터베이스가 없으면 409 `database_required`** 다 — 가입자 표가
291
- * 프로젝트 DB 안이라 부여만 세우면 워커가 뜨는 순간 표가 없다. 부르는 쪽은
292
- * 그 코드를 잡아 `runlot pg create` 를 안내한다.
957
+ * **With no database it is 409 `database_required`** — the user table lives
958
+ * inside the project DB, so standing up the grant alone leaves no table the
959
+ * moment the worker starts. The caller catches that code and points at the
960
+ * `"database": true` declaration — the deploy never sees this code, because
961
+ * its ordering rules it out.
293
962
  */
294
963
  grantAuth(org, name) {
295
964
  return this.json("POST", `${this.projectPath(org, name)}/auth`);
296
965
  }
297
966
  /**
298
- * 설정을 바꾼다 (member). **부분 갱신이다** — 준 칸만 바뀐다. 스위치 하나에
299
- * 전체를 실어 보내면 두 사람이 같은 카드를 만질 때 나중 저장이 앞 저장을
300
- * 덮는다. 부여가 없으면 404 `not_granted`.
967
+ * Changes the settings (member). **A partial update** — only the fields given
968
+ * change. Sending the whole thing on one switch means that when two people
969
+ * touch the same card, the later save overwrites the earlier one. With no
970
+ * grant it is 404 `not_granted`.
301
971
  */
302
972
  updateAuthSettings(org, name, settings) {
303
973
  return this.json("PATCH", `${this.projectPath(org, name)}/auth`, { settings });
304
974
  }
305
975
  /**
306
- * 인증을 해제한다 (admin). **가입자는 안 지워진다** — `runlot_auth` 의 표는
307
- * 프로젝트 DB 에 남고, 다시 켜면 같은 사람들이 그대로 로그인한다.
976
+ * Turns auth off (admin). **The signed-up users are not deleted** — the
977
+ * `runlot_auth` tables stay in the project DB, and turning it back on lets the
978
+ * same people log in unchanged.
308
979
  */
309
980
  revokeAuth(org, name) {
310
981
  return this.json("DELETE", `${this.projectPath(org, name)}/auth`);
311
982
  }
312
983
  /**
313
- * 소셜 프로바이더를 등록하거나 교체한다 (admin). 같은 PUT 이라 멱등이다.
984
+ * Registers or replaces a social provider (admin). It is the same PUT, so it
985
+ * is idempotent.
986
+ *
987
+ * **`clientSecret` cannot be read back.** The callback URL is
988
+ * `https://<host>/__runlot/auth/callback/<provider>` for each host, and the
989
+ * list of hosts is in the response's `hosts`.
314
990
  *
315
- * **`clientSecret` 은 다시 볼 수 없다.** 콜백 URL 은 호스트마다
316
- * `https://<host>/__runlot/auth/callback/<provider>` 이고, 호스트 목록은
317
- * 응답의 `hosts` 에 있다.
991
+ * `issuer` is the base URL of your own GitHub Enterprise Server installation,
992
+ * and only `github` takes one. **This PUT is the whole row** — the same reason
993
+ * `clientSecret` has to be sent every time — so an empty string clears it and
994
+ * puts that provider back on github.com. The key is left out entirely when the
995
+ * argument is omitted, so a caller that does not know about issuers sends the
996
+ * body it always sent.
318
997
  */
319
- setAuthProvider(org, name, provider, clientId, clientSecret) {
320
- return this.json("PUT", `${this.projectPath(org, name)}/auth/providers/${encodeURIComponent(provider)}`, { clientId, clientSecret });
998
+ setAuthProvider(org, name, provider, clientId, clientSecret, issuer) {
999
+ return this.json("PUT", `${this.projectPath(org, name)}/auth/providers/${encodeURIComponent(provider)}`, { clientId, clientSecret, ...(issuer === undefined ? {} : { issuer }) });
321
1000
  }
322
1001
  /**
323
- * 프로바이더를 뗀다 (admin). 그 프로바이더로만 가입한 사람은 로그인할 길을
324
- * 잃지만 사용자 행은 남는다 — 다시 등록하면 같은 계정으로 돌아온다.
1002
+ * Turns on the Runlot provider (admin): "Continue with Runlot", with email,
1003
+ * Google and GitHub at Runlot behind it and nothing to register. 409
1004
+ * `runlot_unavailable` when this deployment has no sign-in broker.
1005
+ */
1006
+ setRunlotAuthProvider(org, name) {
1007
+ return this.json("PUT", `${this.projectPath(org, name)}/auth/providers/runlot`, { kind: "runlot" });
1008
+ }
1009
+ /**
1010
+ * Registers or replaces a generic OIDC provider under a project-chosen id
1011
+ * (admin). The CP reads `<issuer>/.well-known/openid-configuration` when
1012
+ * saving; a failure is 400 `oidc_discovery_failed` quoting the provider.
1013
+ */
1014
+ setOidcAuthProvider(org, name, id, body) {
1015
+ return this.json("PUT", `${this.projectPath(org, name)}/auth/providers/${encodeURIComponent(id)}`, { kind: "oidc", ...body });
1016
+ }
1017
+ /**
1018
+ * The statements that create the `runlot_auth` schema (member). 404 when
1019
+ * login is not turned on for the project.
1020
+ */
1021
+ getAuthSchema(org, name) {
1022
+ return this.json("GET", `${this.projectPath(org, name)}/auth/schema`);
1023
+ }
1024
+ /** The project's sign-in branding with defaults filled (docs/custom-sign-in.md §12.3). */
1025
+ getAuthBranding(org, name) {
1026
+ return this.getAuthBrandingAnswer(org, name).then((a) => a.brand);
1027
+ }
1028
+ /** The GET answer whole: the filled brand plus the methods the chooser would draw now. */
1029
+ getAuthBrandingAnswer(org, name) {
1030
+ return this.json("GET", `${this.projectPath(org, name)}/auth/branding`);
1031
+ }
1032
+ /**
1033
+ * Replaces the whole branding object (member). Validated server-side; a bad
1034
+ * field is 400 `invalid_branding` with `fields: [{path, message}]`.
1035
+ */
1036
+ putAuthBranding(org, name, branding) {
1037
+ return this.json("PUT", `${this.projectPath(org, name)}/auth/branding`, branding)
1038
+ .then((a) => a.brand);
1039
+ }
1040
+ /**
1041
+ * The URL of the rendered chooser with (draft) branding (§12.4). A page, not
1042
+ * JSON: the dashboard puts it in an iframe and the CLI opens it in a browser.
1043
+ * `draft` travels as base64url JSON.
1044
+ */
1045
+ authBrandingPreviewUrl(org, name, opts = {}) {
1046
+ const u = new URL(`${this.projectPath(org, name)}/auth/branding/preview`, this.opts.baseUrl);
1047
+ if (opts.lang)
1048
+ u.searchParams.set("lang", opts.lang);
1049
+ if (opts.theme)
1050
+ u.searchParams.set("theme", opts.theme);
1051
+ if (opts.state)
1052
+ u.searchParams.set("state", opts.state);
1053
+ if (opts.draft)
1054
+ u.searchParams.set("draft", base64urlJson(opts.draft));
1055
+ return u.toString();
1056
+ }
1057
+ /** Sign-in funnel counters for the last `days` days (§9.4). No per-person data. */
1058
+ getAuthFunnel(org, name, days = 30) {
1059
+ return this.json("GET", `${this.projectPath(org, name)}/auth/funnel?days=${encodeURIComponent(String(days))}`);
1060
+ }
1061
+ /**
1062
+ * Removes a provider (admin). Someone who signed up only through that provider
1063
+ * loses their way in, but the user row stays — register it again and they come
1064
+ * back to the same account.
325
1065
  */
326
1066
  deleteAuthProvider(org, name, provider) {
327
1067
  return this.json("DELETE", `${this.projectPath(org, name)}/auth/providers/${encodeURIComponent(provider)}`);
328
1068
  }
329
- // ---- 배포 접근 제어 (docs/access.md §7) ----
1069
+ // ---- Deployment access control (docs/access.md §7) ----
330
1070
  /**
331
- * 이 배포에 누가 닿을 수 있는가. **값은 없다** — 비밀번호도 우회 시크릿도
332
- * 해시로만 살고, 여기 오는 것은 `hasPassword`·`hasBypass` 라는 사실이다.
1071
+ * Who can reach this deployment. **No values** — both the password and the
1072
+ * bypass secret live only as hashes, and what comes back here is the fact that
1073
+ * there is one: `hasPassword` and `hasBypass`.
333
1074
  *
334
- * 정책을 한 번도 안 정한 프로젝트는 `mode: "public"` 에 `updatedAt` 이
335
- * 없다. 화면이 그 둘을 가르는 이유는 §7 — 빈 상태 대신 상태 문장이다.
1075
+ * A project that has never set a policy is `mode: "public"` with no
1076
+ * `updatedAt`. The screen tells those two apart for the reason in §7 — a
1077
+ * sentence about the state instead of an empty state.
336
1078
  */
337
1079
  getAccess(org, name) {
338
1080
  return this.json("GET", `${this.projectPath(org, name)}/access`);
339
1081
  }
340
1082
  /**
341
- * 정책을 바꾼다 (admin). `password` 를 안 보내면 **있던 비밀번호가 남는다** —
342
- * 모드만 바꾸는 저장이 비밀번호를 지우면 되돌아왔을 때 다시 정해야 한다.
1083
+ * Changes the policy (admin). Without a `password`, **the existing password
1084
+ * stays** — if a save that only changes the mode wiped the password, coming
1085
+ * back to that mode would mean setting it again.
343
1086
  */
344
1087
  setAccess(org, name, mode, password) {
345
1088
  return this.json("PUT", `${this.projectPath(org, name)}/access`, { mode, password });
346
1089
  }
347
1090
  /**
348
- * 자동화 우회 시크릿을 만든다 (admin). **값은 이 답에만 있다** — 화면은
349
- * 받은 즉시 한 번 보여주고 다시 못 가져온다. 다시 부르면 옛 값이 죽는다.
1091
+ * Makes a bypass secret for automation (admin). **The value is in this answer
1092
+ * and nowhere else** — the screen shows it once on arrival and can never fetch
1093
+ * it again. Calling again kills the old value.
350
1094
  */
351
1095
  newAccessBypass(org, name) {
352
1096
  return this.json("POST", `${this.projectPath(org, name)}/access/bypass`);
353
1097
  }
354
- /** 우회를 뗀다 (admin). 없는 우회를 떼는 것도 성공이다. */
1098
+ /** Removes the bypass (admin). Removing one that does not exist also succeeds. */
355
1099
  revokeAccessBypass(org, name) {
356
1100
  return this.json("DELETE", `${this.projectPath(org, name)}/access/bypass`);
357
1101
  }
358
1102
  /**
359
- * 보호된 배포로 돌아가는 1 회용 주소를 받는다 (docs/access.md §3.4-3).
1103
+ * Gets a one-time address back into a protected deployment (docs/access.md §3.4-3).
360
1104
  *
361
- * 프로젝트 경로 아래가 **아니다**: 부르는 화면이 아는 것은 호스트네임뿐이고
362
- * (원 요청이 그리로 갔다), org·프로젝트 이름은 서버가 그것에서 유도한다.
363
- * 받은 `redirect` 로 `location.replace` 하는 것이 호출부의 일이다.
1105
+ * It is **not** under the project path: all the calling screen knows is the
1106
+ * hostname (the original request went there), and the server derives the org
1107
+ * and project names from it. Doing `location.replace` with the `redirect` that
1108
+ * comes back is the caller's job.
364
1109
  */
365
1110
  authorizeAccess(to, next) {
366
1111
  return this.json("POST", "/v1/access/authorize", { to, next });
@@ -368,44 +1113,79 @@ export class Client {
368
1113
  listMembers(org) {
369
1114
  return this.json("GET", `/v1/orgs/${encodeURIComponent(org)}/members`);
370
1115
  }
371
- /** 초대가 아니다 — 사용자는 이미 한 번 로그인해 있어야 한다 (404 `user_not_found`). */
1116
+ /** This is not an invite — the user must already have logged in once (404 `user_not_found`). */
372
1117
  addMember(org, provider, subject, role) {
373
1118
  return this.json("POST", `/v1/orgs/${encodeURIComponent(org)}/members`, { provider, subject, role });
374
1119
  }
375
1120
  setMemberRole(org, userId, role) {
376
1121
  return this.json("PUT", `/v1/orgs/${encodeURIComponent(org)}/members/${encodeURIComponent(userId)}`, { role });
377
1122
  }
1123
+ /**
1124
+ * Removing someone else is admin; **removing yourself is leaving**, which
1125
+ * anyone can do (docs/members.md). The last admin can do neither
1126
+ * (409 `last_admin`).
1127
+ */
378
1128
  removeMember(org, userId) {
379
1129
  return this.json("DELETE", `/v1/orgs/${encodeURIComponent(org)}/members/${encodeURIComponent(userId)}`);
380
1130
  }
1131
+ // --- Invites (docs/members.md) ---
1132
+ /** Pending and expired invites (admin). Accepted and revoked ones are history, so they do not come. */
1133
+ listInvites(org) {
1134
+ return this.json("GET", `/v1/orgs/${encodeURIComponent(org)}/invites`);
1135
+ }
1136
+ /**
1137
+ * Invites by email (admin). **Calling again with the same address is a
1138
+ * resend** — the same row is updated rather than a new one created, and the
1139
+ * server gives 200 instead of 201.
1140
+ */
1141
+ createInvite(org, email, role) {
1142
+ return this.json("POST", `/v1/orgs/${encodeURIComponent(org)}/invites`, { email, role });
1143
+ }
1144
+ /** Revokes an invite (admin). Mail that has not gone out yet does not go out. */
1145
+ revokeInvite(org, inviteId) {
1146
+ return this.json("DELETE", `/v1/orgs/${encodeURIComponent(org)}/invites/${encodeURIComponent(inviteId)}`);
1147
+ }
1148
+ /**
1149
+ * A preview of the invite. **No session needed** — whoever got the link has
1150
+ * not logged in yet, and they need to know what they are accepting before
1151
+ * they do.
1152
+ */
1153
+ getInvite(token) {
1154
+ return this.json("GET", `/v1/invites/${encodeURIComponent(token)}`);
1155
+ }
1156
+ /** Accepts (login required). If they are already a member the role does not change. */
1157
+ acceptInvite(token) {
1158
+ return this.json("POST", `/v1/invites/${encodeURIComponent(token)}/accept`);
1159
+ }
381
1160
  // --- domains: D1 hostnames methods ---
382
- /** 기본 호스트네임과 커스텀 도메인이 함께 온다 (viewer). */
1161
+ /** The default hostname and the custom domains come together (viewer). */
383
1162
  listHostnames(org, name) {
384
1163
  return this.json("GET", `${this.projectPath(org, name)}/hostnames`);
385
1164
  }
386
1165
  /**
387
- * 커스텀 도메인을 건다 (member).
1166
+ * Attaches a custom domain (member).
388
1167
  *
389
- * 멱등이다 — 같은 이름을 다시 보내면 있던 행이 그대로 온다. 응답의 `verify`
390
- * 가 고객이 넣어야 하는 CNAME·TXT 다.
1168
+ * Idempotent — sending the same name again returns the existing row
1169
+ * unchanged. The response's `verify` is the CNAME and TXT the customer has to
1170
+ * add.
391
1171
  */
392
- addHostname(org, name, hostname) {
393
- return this.json("POST", `${this.projectPath(org, name)}/hostnames`, { hostname });
1172
+ addHostname(org, name, hostname, role) {
1173
+ return this.json("POST", `${this.projectPath(org, name)}/hostnames`, role === undefined ? { hostname } : { hostname, role });
394
1174
  }
395
- /** 배경 검증과 같은 판정을 즉시 부른다 (member). */
1175
+ /** Runs the same check the background verifier makes, right now (member). */
396
1176
  verifyHostname(org, name, host) {
397
1177
  return this.json("POST", `${this.projectPath(org, name)}/hostnames/${encodeURIComponent(host)}/verify`);
398
1178
  }
399
- /** 커스텀 도메인을 뗀다 (member). 기본 호스트네임은 400 이다. */
1179
+ /** Detaches a custom domain (member). The default hostname gives a 400. */
400
1180
  deleteHostname(org, name, host) {
401
1181
  return this.json("DELETE", `${this.projectPath(org, name)}/hostnames/${encodeURIComponent(host)}`);
402
1182
  }
403
1183
  // --- domains: D2 dns methods ---
404
- /** 이 조직의 존 목록. `rrsets` 는 없다 — 단건 조회에만 실려요. */
1184
+ /** The organization's zones. No `rrsets` — those ride only on a single-zone lookup. */
405
1185
  listZones(org) {
406
1186
  return this.json("GET", this.dnsPath(org));
407
1187
  }
408
- /** 멱등이에요. 이미 있는 존은 그대로 돌아와요. */
1188
+ /** Idempotent. A zone that already exists comes back unchanged. */
409
1189
  createZone(org, name) {
410
1190
  return this.json("POST", this.dnsPath(org), { name });
411
1191
  }
@@ -416,8 +1196,9 @@ export class Client {
416
1196
  return this.json("DELETE", `${this.dnsPath(org)}/${encodeURIComponent(zone)}`);
417
1197
  }
418
1198
  /**
419
- * rrset 하나를 **통째로** 바꿔요. `records` 가 그 (이름, 타입) 의 새 전부라,
420
- * 값 하나를 더하려면 지금 값을 함께 보내야 해요.
1199
+ * Replaces one rrset **whole**. `records` is the complete new set for that
1200
+ * (name, type), so adding a single value means sending the current ones with
1201
+ * it.
421
1202
  */
422
1203
  putRRset(org, zone, name, type, ttl, records) {
423
1204
  return this.json("PUT", this.rrsetPath(org, zone, name, type), { ttl, records });
@@ -433,39 +1214,40 @@ export class Client {
433
1214
  setZoneDS(org, zone, ds) {
434
1215
  return this.json("PUT", `${this.dnsPath(org)}/${encodeURIComponent(zone)}/dnssec/ds`, { ds });
435
1216
  }
436
- /** DNS 표면의 공통 접두. */
1217
+ /** The shared prefix of the DNS surface. */
437
1218
  dnsPath(org) {
438
1219
  return `/v1/orgs/${encodeURIComponent(org)}/dns/zones`;
439
1220
  }
440
- /** `@` 도 `*` 도 이름으로 와요. 네 군데에 같은 문자열을 적지 않아요. */
1221
+ /** Both `@` and `*` arrive as a name. Keeps the same string out of four places. */
441
1222
  rrsetPath(org, zone, name, type) {
442
1223
  return (`${this.dnsPath(org)}/${encodeURIComponent(zone)}` +
443
1224
  `/rrsets/${encodeURIComponent(name)}/${encodeURIComponent(type)}`);
444
1225
  }
445
1226
  // --- domains: D3 domains methods ---
446
1227
  /**
447
- * 이름을 찾아본다 (member 이상).
1228
+ * Looks a name up (member or above).
448
1229
  *
449
- * `priceCents` 는 첫 등록 1 년, `renewalCents` 는 갱신 1 년이다. 둘이
450
- * 나뉘어 있는 이유는 첫해 할인이 흔해서다 — 하나로 접으면 "1 달러에 사서
451
- * 다음 해 15 달러" 를 화면이 말할 수 없다.
1230
+ * `priceCents` is the first year of registration; `renewalCents` is one year
1231
+ * of renewal. They are separate because a first-year discount is common —
1232
+ * folded into one, the screen cannot say "buy it for $1, then $15 next year".
452
1233
  */
453
1234
  checkDomains(org, names) {
454
1235
  return this.json("POST", `${this.domainsPath(org)}/check`, { names });
455
1236
  }
456
1237
  /**
457
- * 도메인을 산다 (admin — 돈을 써요).
1238
+ * Buys a domain (admin — this spends money).
458
1239
  *
459
- * **ICANN 검증 메일이 `contact.email` 로 가요.** 화면은 사기 전에 그
460
- * 사실을 알려야 해요 (docs/domains.md §5.5).
1240
+ * **The ICANN verification mail goes to `contact.email`.** The screen has to
1241
+ * say so before the purchase (docs/domains.md §5.5).
461
1242
  *
462
- * 같은 요청을 다시 보내는 것이 안전해요 — 끝난 도메인이면 그대로 오고,
463
- * 중간에 멈춘 구매면 그 자리에서 이어 가요.
1243
+ * Sending the same request again is safe — a finished domain comes back
1244
+ * unchanged, and a purchase that stopped part way resumes from where it
1245
+ * stopped.
464
1246
  */
465
1247
  purchaseDomain(org, body) {
466
1248
  return this.json("POST", this.domainsPath(org), body);
467
1249
  }
468
- /** 이미 가진 도메인을 가져와요 (admin). 등록기관을 부르지 않고 존만 만들어요. */
1250
+ /** Imports a domain you already own (admin). Creates the zone only; the registrar is not called. */
469
1251
  importDomain(org, name) {
470
1252
  return this.json("POST", `${this.domainsPath(org)}/import`, { name });
471
1253
  }
@@ -479,11 +1261,11 @@ export class Client {
479
1261
  return this.json("POST", `${this.domainPath(org, name)}/renew`, { years });
480
1262
  }
481
1263
  /**
482
- * 자동 갱신 **의사**만 바꿔요.
1264
+ * Changes only the **intent** to auto-renew.
483
1265
  *
484
- * 등록기관 쪽 자동 갱신은 그대로 켜져 있어요 — 도메인은 하루 늦으면 잃는
485
- * 자산이라 우리가 먼저 갱신하고 뒤에 청구해요. 화면은 이 사실을 함께
486
- * 말해야 해요.
1266
+ * Auto-renew at the registrar stays on — a domain is an asset you lose if you
1267
+ * are a day late, so we renew first and bill afterwards. The screen has to say
1268
+ * this alongside.
487
1269
  */
488
1270
  setDomainAutoRenew(org, name, enabled) {
489
1271
  return this.json("POST", `${this.domainPath(org, name)}/auto-renew`, { enabled });
@@ -491,29 +1273,131 @@ export class Client {
491
1273
  setDomainLock(org, name, locked) {
492
1274
  return this.json("POST", `${this.domainPath(org, name)}/lock`, { locked });
493
1275
  }
494
- /** 이전 코드예요. 감사에 발급 사실이 남고 **코드는 남지 않아요**. */
1276
+ /** The transfer auth code. The audit records that one was issued and **not the code itself**. */
495
1277
  domainAuthCode(org, name) {
496
1278
  return this.json("POST", `${this.domainPath(org, name)}/auth-code`);
497
1279
  }
498
- /** 지금 등록기관에서 다시 읽어요 (member). */
1280
+ /** Re-reads from the registrar right now (member). */
499
1281
  syncDomain(org, name) {
500
1282
  return this.json("POST", `${this.domainPath(org, name)}/sync`);
501
1283
  }
502
- /** 도메인 표면의 공통 접두. 열 군데에 같은 문자열을 적지 않아요. */
1284
+ /** The shared prefix of the domain surface. Keeps the same string out of ten places. */
503
1285
  domainsPath(org) {
504
1286
  return `/v1/orgs/${encodeURIComponent(org)}/domains`;
505
1287
  }
506
1288
  domainPath(org, name) {
507
1289
  return `${this.domainsPath(org)}/${encodeURIComponent(name)}`;
508
1290
  }
509
- /** 프로젝트 표면의 공통 접두다. */
1291
+ /** The shared prefix of the project surface. */
510
1292
  projectPath(org, name) {
511
1293
  return `/v1/orgs/${encodeURIComponent(org)}/projects/${encodeURIComponent(name)}`;
512
1294
  }
513
- /** 데이터베이스 표면의 공통 접두다. 다섯 군데에 같은 문자열을 적지 않는다. */
1295
+ /** The shared prefix of the database surface. Keeps the same string out of five places. */
514
1296
  dbPath(org, name) {
515
1297
  return `/v1/orgs/${encodeURIComponent(org)}/projects/${encodeURIComponent(name)}/database`;
516
1298
  }
1299
+ // ---- Self-hosted Git (docs/git-hosting.md §12.1, §19) ----
1300
+ //
1301
+ // **git does the repository work and we handle only the metadata.** That is
1302
+ // why there is nothing like `pushRepo` here — an API that wraps git either
1303
+ // reimplements every one of git's flags or boxes the user in.
1304
+ //
1305
+ // A repository **belongs to a project**. That is why every method starts with
1306
+ // (org, project) — the same shape as the database and the secrets.
1307
+ listRepos(org, project) {
1308
+ return this.json("GET", this.repoPath(org, project));
1309
+ }
1310
+ createRepo(org, project, body) {
1311
+ return this.json("POST", this.repoPath(org, project), body);
1312
+ }
1313
+ getRepo(org, project, name) {
1314
+ return this.json("GET", `${this.repoPath(org, project)}/${encodeURIComponent(name)}`);
1315
+ }
1316
+ updateRepo(org, project, name, body) {
1317
+ return this.json("PATCH", `${this.repoPath(org, project)}/${encodeURIComponent(name)}`, body);
1318
+ }
1319
+ deleteRepo(org, project, name) {
1320
+ return this.json("DELETE", `${this.repoPath(org, project)}/${encodeURIComponent(name)}`);
1321
+ }
1322
+ /** The ref history. The lead for recovering a commit lost to a force-push is here. */
1323
+ listRefUpdates(org, project, name) {
1324
+ return this.json("GET", `${this.repoPath(org, project)}/${encodeURIComponent(name)}/ref-updates`);
1325
+ }
1326
+ // Push-to-deploy (docs/code/push-to-deploy). The hook hangs off the
1327
+ // repository and the builds off the **project**, because a build outlives the
1328
+ // repository it came from.
1329
+ getDeployHook(org, project, name) {
1330
+ return this.json("GET", `${this.repoPath(org, project)}/${encodeURIComponent(name)}/deploy-hook`);
1331
+ }
1332
+ setDeployHook(org, project, name, body) {
1333
+ return this.json("PUT", `${this.repoPath(org, project)}/${encodeURIComponent(name)}/deploy-hook`, body);
1334
+ }
1335
+ deleteDeployHook(org, project, name) {
1336
+ return this.json("DELETE", `${this.repoPath(org, project)}/${encodeURIComponent(name)}/deploy-hook`);
1337
+ }
1338
+ /** Build a commit without pushing. Omit `commitSha` for the hooked branch's tip. */
1339
+ deployRepoNow(org, project, name, commitSha) {
1340
+ return this.json("POST", `${this.repoPath(org, project)}/${encodeURIComponent(name)}/deploy`, commitSha === undefined ? {} : { commitSha });
1341
+ }
1342
+ listBuilds(org, project, limit) {
1343
+ const q = limit === undefined ? "" : `?limit=${limit}`;
1344
+ return this.json("GET", `${this.projectPath(org, project)}/builds${q}`);
1345
+ }
1346
+ getBuild(org, project, buildId) {
1347
+ return this.json("GET", `${this.projectPath(org, project)}/builds/${encodeURIComponent(buildId)}`);
1348
+ }
1349
+ /**
1350
+ * A build's output. It comes back as **text**, not JSON — see the endpoint's
1351
+ * description. `json()` would try to parse it and fail on the first line.
1352
+ */
1353
+ getBuildLog(org, project, buildId) {
1354
+ return this.text("GET", `${this.projectPath(org, project)}/builds/${encodeURIComponent(buildId)}/log`);
1355
+ }
1356
+ cancelBuild(org, project, buildId) {
1357
+ return this.json("POST", `${this.projectPath(org, project)}/builds/${encodeURIComponent(buildId)}/cancel`);
1358
+ }
1359
+ listSSHKeys() {
1360
+ return this.json("GET", "/v1/me/ssh-keys");
1361
+ }
1362
+ addSSHKey(publicKey, name) {
1363
+ return this.json("POST", "/v1/me/ssh-keys", { publicKey, name });
1364
+ }
1365
+ deleteSSHKey(keyId) {
1366
+ return this.json("DELETE", `/v1/me/ssh-keys/${encodeURIComponent(keyId)}`);
1367
+ }
1368
+ listAccessTokens() {
1369
+ return this.json("GET", "/v1/me/tokens");
1370
+ }
1371
+ /** The plaintext is carried in this response **once** and never again. */
1372
+ createAccessToken(body) {
1373
+ return this.json("POST", "/v1/me/tokens", body);
1374
+ }
1375
+ revokeAccessToken(tokenId) {
1376
+ return this.json("DELETE", `/v1/me/tokens/${encodeURIComponent(tokenId)}`);
1377
+ }
1378
+ // ---- Browsing (docs/git-hosting.md §12.2) ----
1379
+ getRepoRefs(org, project, name) {
1380
+ return this.json("GET", `${this.repoPath(org, project)}/${encodeURIComponent(name)}/refs`);
1381
+ }
1382
+ getRepoTree(org, project, name, ref = "", path = "") {
1383
+ return this.json("GET", `${this.repoPath(org, project)}/${encodeURIComponent(name)}/tree${gitQuery(ref, path)}`);
1384
+ }
1385
+ getRepoBlob(org, project, name, ref = "", path = "") {
1386
+ return this.json("GET", `${this.repoPath(org, project)}/${encodeURIComponent(name)}/blob${gitQuery(ref, path)}`);
1387
+ }
1388
+ getRepoCommits(org, project, name, ref = "", limit) {
1389
+ const q = new URLSearchParams();
1390
+ if (ref !== "")
1391
+ q.set("ref", ref);
1392
+ if (limit !== undefined)
1393
+ q.set("limit", String(limit));
1394
+ const qs = q.size > 0 ? `?${q.toString()}` : "";
1395
+ return this.json("GET", `${this.repoPath(org, project)}/${encodeURIComponent(name)}/commits${qs}`);
1396
+ }
1397
+ /** The shared prefix of the repository surface. It sits under the project (§19). */
1398
+ repoPath(org, project) {
1399
+ return `${this.projectPath(org, project)}/repos`;
1400
+ }
517
1401
  rollback(org, name, version) {
518
1402
  return this.json("POST", `/v1/orgs/${encodeURIComponent(org)}/projects/${encodeURIComponent(name)}/rollback`, { version });
519
1403
  }