@sixb/cli 0.2.5 → 0.2.7

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.
Files changed (67) hide show
  1. package/dist/commands/api.d.ts.map +1 -1
  2. package/dist/commands/app.d.ts.map +1 -1
  3. package/dist/commands/check.d.ts +4 -0
  4. package/dist/commands/check.d.ts.map +1 -1
  5. package/dist/commands/db-migrate.d.ts +2 -0
  6. package/dist/commands/db-migrate.d.ts.map +1 -1
  7. package/dist/commands/deploy.d.ts +0 -20
  8. package/dist/commands/deploy.d.ts.map +1 -1
  9. package/dist/commands/env.d.ts.map +1 -1
  10. package/dist/commands/worker-group.d.ts.map +1 -1
  11. package/dist/commands/worker.d.ts.map +1 -1
  12. package/dist/lib/command-line.d.ts +16 -16
  13. package/dist/lib/command-line.d.ts.map +1 -1
  14. package/dist/lib/deploy-release.d.ts.map +1 -1
  15. package/dist/lib/deploy-source.d.ts +2 -0
  16. package/dist/lib/deploy-source.d.ts.map +1 -1
  17. package/dist/lib/env-config.d.ts.map +1 -1
  18. package/dist/lib/role-lifecycle.d.ts +8 -1
  19. package/dist/lib/role-lifecycle.d.ts.map +1 -1
  20. package/dist/lib/storage-migration.d.ts +7 -0
  21. package/dist/lib/storage-migration.d.ts.map +1 -1
  22. package/dist/lib/worker-registry.d.ts +1 -0
  23. package/dist/lib/worker-registry.d.ts.map +1 -1
  24. package/dist/runner/computer-connection.d.ts.map +1 -1
  25. package/dist/tui/app.d.ts +2 -0
  26. package/dist/tui/app.d.ts.map +1 -1
  27. package/dist/tui/moves.d.ts +62 -0
  28. package/dist/tui/moves.d.ts.map +1 -0
  29. package/dist/tui/parts.d.ts.map +1 -1
  30. package/dist/tui/settings.d.ts +2 -0
  31. package/dist/tui/settings.d.ts.map +1 -1
  32. package/dist/tui/transcript.d.ts +13 -6
  33. package/dist/tui/transcript.d.ts.map +1 -1
  34. package/dist/ui/deploy-screens.d.ts +1 -26
  35. package/dist/ui/deploy-screens.d.ts.map +1 -1
  36. package/dist/ui/screens.d.ts +8 -0
  37. package/dist/ui/screens.d.ts.map +1 -1
  38. package/package.json +21 -21
  39. package/src/commands/agent.ts +1 -1
  40. package/src/commands/api.ts +20 -10
  41. package/src/commands/app.ts +15 -7
  42. package/src/commands/check.ts +87 -49
  43. package/src/commands/db-migrate.ts +25 -1
  44. package/src/commands/deploy.ts +16 -186
  45. package/src/commands/dev-runner.ts +1 -1
  46. package/src/commands/env.ts +15 -5
  47. package/src/commands/worker-group.ts +36 -9
  48. package/src/commands/worker.ts +27 -9
  49. package/src/index.tsx +11 -27
  50. package/src/lib/command-line.ts +19 -53
  51. package/src/lib/deploy-release.ts +3 -4
  52. package/src/lib/deploy-source.ts +15 -0
  53. package/src/lib/env-config.ts +1 -3
  54. package/src/lib/role-lifecycle.ts +48 -8
  55. package/src/lib/storage-migration.ts +33 -1
  56. package/src/lib/worker-registry.ts +4 -1
  57. package/src/runner/computer-connection.ts +7 -1
  58. package/src/tui/app.tsx +183 -38
  59. package/src/tui/moves.ts +221 -0
  60. package/src/tui/parts.ts +7 -0
  61. package/src/tui/settings.ts +5 -0
  62. package/src/tui/transcript.tsx +50 -14
  63. package/src/ui/deploy-screens.ts +11 -112
  64. package/src/ui/screens.ts +23 -0
  65. package/dist/lib/github-ci.d.ts +0 -49
  66. package/dist/lib/github-ci.d.ts.map +0 -1
  67. package/src/lib/github-ci.ts +0 -262
@@ -1,10 +1,15 @@
1
1
  /** @jsxImportSource @opentui/react */
2
2
  import { CodeRenderable, type MarkdownOptions, type SyntaxStyle } from "@opentui/core"
3
3
  import { useRenderer } from "@opentui/react"
4
- import type { ListAgentThreadApprovalsResponses, ListAgentThreadRunsResponses } from "@sixb/client"
5
- import { useEffect, useState } from "react"
4
+ import type {
5
+ GetAgentThreadResponses,
6
+ ListAgentThreadApprovalsResponses,
7
+ ListAgentThreadRunsResponses,
8
+ } from "@sixb/client"
9
+ import { Fragment, type ReactNode, useEffect, useState } from "react"
6
10
  import { duration, friendlyPath, plural, runFailureText, type ToolLine, toolLine } from "./format"
7
11
  import { steadyMarkdown } from "./markdown"
12
+ import { type PlaceNames, placeName, runPlace, transcriptMoves } from "./moves"
8
13
  import {
9
14
  type ApprovalOutcome,
10
15
  approvalOutcomes,
@@ -12,7 +17,6 @@ import {
12
17
  type Part,
13
18
  type ShownMessage,
14
19
  } from "./parts"
15
- import { placeLabel } from "./settings"
16
20
  import type { TuiColors } from "./theme"
17
21
  import { BOLD, ITALIC, useNow, useSpinner } from "./ui"
18
22
 
@@ -32,7 +36,8 @@ export function Transcript({
32
36
  live,
33
37
  approvals,
34
38
  modelNames,
35
- computerRuns,
39
+ thread,
40
+ names,
36
41
  width,
37
42
  folder,
38
43
  approvalChoice,
@@ -44,8 +49,16 @@ export function Transcript({
44
49
  readonly live: LiveRun | null
45
50
  readonly approvals: readonly Approval[]
46
51
  readonly modelNames: ModelNames
47
- /** Whether the thread's turns run on its owner's computer. */
48
- readonly computerRuns: boolean
52
+ /**
53
+ * Where the conversation runs now, when it last moved, and when it began: a fork's copies
54
+ * predate it.
55
+ */
56
+ readonly thread: Pick<
57
+ GetAgentThreadResponses[200],
58
+ "runsOn" | "computer" | "movedAt" | "createdAt"
59
+ > | null
60
+ /** The computers' and owner's names its places are written with. */
61
+ readonly names: PlaceNames
49
62
  /** The terminal's width: rows that must stay one line are cut to it. */
50
63
  readonly width: number
51
64
  /** The folder a computer's turns work in: paths in it are shown relative to it. */
@@ -61,17 +74,39 @@ export function Transcript({
61
74
  const liveShown =
62
75
  live &&
63
76
  !messages.some((message) => message.runId === live.runId && message.role === "assistant")
77
+
78
+ // Each turn says where it ran, and a line marks every move between two of them.
79
+ const moves = transcriptMoves({
80
+ thread,
81
+ messages,
82
+ shownIds: new Set(shown.map((message) => message.id)),
83
+ runs,
84
+ names,
85
+ })
86
+ const withMove = (message: ShownMessage, body: ReactNode) => {
87
+ const moved = moves.get(message.id)
88
+ return (
89
+ <Fragment key={message.id}>
90
+ {body}
91
+ {moved ? <text fg={colors.faint}>{`◇ ${moved}`}</text> : null}
92
+ </Fragment>
93
+ )
94
+ }
95
+
64
96
  return (
65
97
  <box flexDirection="column" gap={1}>
66
98
  {shown.map((message, index) => {
67
- if (message.role === "user")
68
- return <UserMessage key={message.id} colors={colors} message={message} />
99
+ if (message.role === "user") {
100
+ return withMove(message, <UserMessage colors={colors} message={message} />)
101
+ }
102
+
69
103
  const next = shown[index + 1]
70
104
  // A turn's meta goes under its last message: a resumed turn answers in several.
71
105
  const lastOfRun = !next || next.runId !== message.runId
72
106
  const run = message.runId ? runsById.get(message.runId) : undefined
73
- return (
74
- <box key={message.id} flexDirection="column" gap={1}>
107
+ return withMove(
108
+ message,
109
+ <box flexDirection="column" gap={1}>
75
110
  {message.compaction ? (
76
111
  <CompactionLine colors={colors} contextFull={message.compaction.contextFull} />
77
112
  ) : null}
@@ -89,7 +124,7 @@ export function Transcript({
89
124
  colors={colors}
90
125
  run={run}
91
126
  modelNames={modelNames}
92
- computerRuns={computerRuns}
127
+ place={placeName(runPlace(run), names)}
93
128
  waiting={approvals.some((approval) => approval.runId === run.id)}
94
129
  />
95
130
  ) : null}
@@ -467,13 +502,14 @@ function RunMeta({
467
502
  colors,
468
503
  run,
469
504
  modelNames,
470
- computerRuns,
505
+ place,
471
506
  waiting,
472
507
  }: {
473
508
  readonly colors: TuiColors
474
509
  readonly run: Run
475
510
  readonly modelNames: ModelNames
476
- readonly computerRuns: boolean
511
+ /** Where it ran: `Cloud`, or a folder and its computer. */
512
+ readonly place: string
477
513
  /** One of its calls still waits for the person. */
478
514
  readonly waiting: boolean
479
515
  }) {
@@ -500,7 +536,7 @@ function RunMeta({
500
536
  return (
501
537
  <text>
502
538
  <span fg={colors.blue}>{" ▰ "}</span>
503
- <span fg={colors.text}>{placeLabel(computerRuns ? "computer" : "cloud")}</span>
539
+ <span fg={colors.text}>{place}</span>
504
540
  {items.map((item) => (
505
541
  <span key={item} fg={colors.muted}>{` · ${item}`}</span>
506
542
  ))}
@@ -1,10 +1,4 @@
1
- import type {
2
- DeployAccessKey,
3
- DeployCheck,
4
- DeployCommand,
5
- DeployRelease,
6
- DeployStatus,
7
- } from "@sixb/core/deploy"
1
+ import type { DeployCheck, DeployCommand, DeployRelease, DeployStatus } from "@sixb/core/deploy"
8
2
  import {
9
3
  commands,
10
4
  header,
@@ -196,8 +190,7 @@ export function deployStatusView({
196
190
 
197
191
  const CHECK_STATUS = {
198
192
  ok: "ok",
199
- fixable: "warn",
200
- manual: "idle",
193
+ fail: "idle",
201
194
  warning: "warn",
202
195
  } as const satisfies Record<DeployCheck["status"], Status>
203
196
 
@@ -210,13 +203,15 @@ export function deployChecksView({
210
203
  location: string
211
204
  checks: readonly DeployCheck[]
212
205
  }): string {
213
- const blocking = checks.filter((check) => check.status === "fixable" || check.status === "manual")
206
+ const blocking = checks.filter((check) => check.status === "fail")
214
207
  const warnings = checks.filter((check) => check.status === "warning")
215
- const next = blocking.some((check) => check.status === "fixable")
216
- ? "sixb deploy setup"
217
- : blocking.length > 0
218
- ? "the steps above, then sixb deploy check"
219
- : "sixb deploy"
208
+ const next = blocking.length > 0 ? "the steps above, then sixb deploy check" : "sixb deploy"
209
+ // Unwrapped and together, so they paste into a root shell on the server as they are.
210
+ const fixes = [
211
+ ...new Set(
212
+ checks.filter((check) => check.status !== "ok").flatMap((check) => check.commands ?? [])
213
+ ),
214
+ ]
220
215
 
221
216
  return screen(
222
217
  header("deploy check", location),
@@ -237,107 +232,11 @@ export function deployChecksView({
237
232
  `${name} is ready to deploy`,
238
233
  warnings.length > 0 ? `${warnings.length} to look at` : undefined
239
234
  ),
235
+ fixes.length > 0 ? section("Run once on the server, as root", commands(fixes)) : undefined,
240
236
  nextStep(next)
241
237
  )
242
238
  }
243
239
 
244
- export function deployCiView({
245
- name,
246
- repo,
247
- environment,
248
- branch,
249
- credential,
250
- secrets,
251
- retired,
252
- workflow,
253
- token,
254
- }: {
255
- name: string
256
- repo: string
257
- environment: string
258
- branch: string
259
- credential: string
260
- secrets: readonly string[]
261
- retired: readonly DeployAccessKey[]
262
- workflow: { readonly path: string; readonly state: "written" | "unchanged" | "kept" }
263
- token: {
264
- readonly name: string
265
- readonly submodules: readonly {
266
- readonly path: string
267
- readonly url: string
268
- readonly repo: string | null
269
- }[]
270
- } | null
271
- }): string {
272
- const items: Row[] = [
273
- { label: "Key", status: "ok", value: credential },
274
- { label: "Secrets", status: "ok", value: secrets.join(", ") },
275
- {
276
- label: "Older keys",
277
- status: "ok",
278
- value:
279
- retired.length === 0
280
- ? "none to revoke"
281
- : `revoked ${retired.map((key) => key.fingerprint).join(", ")}`,
282
- },
283
- {
284
- label: "Workflow",
285
- status: "ok",
286
- value: {
287
- written: workflow.path,
288
- unchanged: `${workflow.path} (unchanged)`,
289
- kept: `${workflow.path} (yours, kept: it differs from what this command writes; delete it and run again to start over)`,
290
- }[workflow.state],
291
- },
292
- ...(token
293
- ? [
294
- {
295
- label: "Token",
296
- status: "idle" as const,
297
- value: `${token.submodules.map((submodule) => submodule.path).join(", ")} ${token.submodules.length === 1 ? "is" : "are"} private, and CI cannot read ${token.submodules.length === 1 ? "it" : "them"} with its own token.`,
298
- remedy: `Create a fine-grained token with Contents: read on ${token.submodules.map((submodule) => submodule.repo ?? submodule.url).join(", ")}, then run \`gh secret set ${token.name} --env ${environment} --repo ${repo}\`.`,
299
- },
300
- ]
301
- : []),
302
- ]
303
- const next =
304
- workflow.state === "written"
305
- ? `commit ${workflow.path} and push to ${branch}.`
306
- : `push to ${branch} to deploy.`
307
-
308
- return screen(
309
- stack(header("deploy ci", repo), tone.muted(`environment ${environment}`)),
310
- rows(items),
311
- headline(
312
- token ? "warn" : "ok",
313
- `${name} deploys from GitHub Actions on every push to ${branch}`
314
- ),
315
- nextStep(next)
316
- )
317
- }
318
-
319
- export function deployAccessView({
320
- title,
321
- keys,
322
- }: {
323
- title: string
324
- keys: readonly DeployAccessKey[]
325
- }): string {
326
- // Two lines a key: a fingerprint and a long comment do not fit side by side in 80 columns.
327
- const list =
328
- keys.length === 0
329
- ? tone.muted("No keys.")
330
- : keys
331
- .map((key) =>
332
- stack(
333
- `${key.comment || "(no comment)"}${key.restricted ? tone.warn(" restricted") : ""}`,
334
- tone.muted(`${key.type} ${key.fingerprint}`)
335
- )
336
- )
337
- .join("\n")
338
- return screen(header(), list, headline("ok", title))
339
- }
340
-
341
240
  /** The one thing to do next: a command to run, or what to do in words. */
342
241
  function nextStep(next: string): string {
343
242
  return section("Next steps", next.startsWith("sixb ") ? commands([next]) : remedy(next))
package/src/ui/screens.ts CHANGED
@@ -421,6 +421,29 @@ export function dbMigrateView({
421
421
  )
422
422
  }
423
423
 
424
+ export function dbMigrateCheckView({
425
+ projectId,
426
+ pending,
427
+ }: {
428
+ projectId: string
429
+ /** The storage adapters with migrations to apply. */
430
+ pending: readonly { readonly adapterId: string; readonly reason?: string }[]
431
+ }): string {
432
+ if (pending.length === 0) {
433
+ return screen(headline("ok", "No database migrations pending", projectId))
434
+ }
435
+
436
+ return screen(
437
+ stack(
438
+ headline("warn", "Database migrations pending", projectId),
439
+ ...pending.map(
440
+ (status) =>
441
+ ` ${tone.faint(glyph.rule)} ${tone.muted(`${status.adapterId}: ${status.reason ?? ""}`)}`
442
+ )
443
+ )
444
+ )
445
+ }
446
+
424
447
  export function lakeCheckView({
425
448
  projectId,
426
449
  warnings = [],
@@ -1,49 +0,0 @@
1
- /** The GitHub environment that holds the deploy secrets and gates the deploy job. */
2
- export declare const CI_ENVIRONMENT = "production";
3
- /** The secret a private submodule's checkout reads. */
4
- export declare const SUBMODULE_TOKEN_SECRET = "SIXB_GITHUB_TOKEN";
5
- export interface GitHubRepo {
6
- /** `owner/name`. */
7
- readonly name: string;
8
- readonly defaultBranch: string;
9
- }
10
- export interface Submodule {
11
- readonly path: string;
12
- readonly url: string;
13
- /** `owner/name` when the submodule lives on GitHub. */
14
- readonly repo: string | null;
15
- }
16
- export interface WorkflowInput {
17
- /** The deployment's name. */
18
- readonly name: string;
19
- readonly branch: string;
20
- /** The project's directory relative to the repository root, `"."` at the root. */
21
- readonly projectPath: string;
22
- /** The `package.json` that pins Bun, relative to the repository root. */
23
- readonly bunVersionFile: string | null;
24
- /** GitHub secret names, by the environment variable the install lines read. */
25
- readonly secrets: Readonly<Record<string, string>>;
26
- readonly install: readonly string[];
27
- readonly submodules: "none" | "public" | "private";
28
- }
29
- /** A GitHub Actions workflow that deploys on every push to `branch`. */
30
- export declare function renderWorkflow(input: WorkflowInput): string;
31
- /** Where the workflow for a deployment lives, relative to the repository root. */
32
- export declare function workflowPath(name: string): string;
33
- /** The GitHub secret for one of a deployment's variables; a repository may deploy several. */
34
- export declare function secretName(deployment: string, variable: string): string;
35
- /** The `package.json` that pins Bun for the project, relative to the repository root. */
36
- export declare function bunVersionFile(projectDir: string, repoRoot: string): Promise<string | null>;
37
- /** The submodules `.gitmodules` lists, with the GitHub repository behind each. */
38
- export declare function readSubmodules(repoRoot: string, repo: GitHubRepo): Promise<Submodule[]>;
39
- /** `owner/name` for a GitHub remote URL, resolving a relative one against `parent`. */
40
- export declare function githubRepoOf(url: string, parent: string): string | null;
41
- export declare function currentRepo(cwd: string): Promise<GitHubRepo>;
42
- /** Whether CI's own token cannot read `repo`. A repository this login cannot see counts. */
43
- export declare function isPrivate(repo: string): Promise<boolean>;
44
- /** Creates the environment when it is missing. An existing one keeps its protection rules. */
45
- export declare function ensureEnvironment(repo: GitHubRepo): Promise<void>;
46
- export declare function setSecret(repo: GitHubRepo, name: string, value: string): Promise<void>;
47
- /** Whether the environment or the repository has the secret. */
48
- export declare function hasSecret(repo: GitHubRepo, name: string): Promise<boolean>;
49
- //# sourceMappingURL=github-ci.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"github-ci.d.ts","sourceRoot":"","sources":["../../src/lib/github-ci.ts"],"names":[],"mappings":"AAGA,qFAAqF;AACrF,eAAO,MAAM,cAAc,eAAe,CAAA;AAE1C,uDAAuD;AACvD,eAAO,MAAM,sBAAsB,sBAAsB,CAAA;AAMzD,MAAM,WAAW,UAAU;IACzB,oBAAoB;IACpB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAA;CAC/B;AAED,MAAM,WAAW,SAAS;IACxB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;IACpB,uDAAuD;IACvD,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAA;CAC7B;AAED,MAAM,WAAW,aAAa;IAC5B,6BAA6B;IAC7B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,kFAAkF;IAClF,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAA;IAC5B,yEAAyE;IACzE,QAAQ,CAAC,cAAc,EAAE,MAAM,GAAG,IAAI,CAAA;IACtC,+EAA+E;IAC/E,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAA;IAClD,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,CAAA;IACnC,QAAQ,CAAC,UAAU,EAAE,MAAM,GAAG,QAAQ,GAAG,SAAS,CAAA;CACnD;AAED,wEAAwE;AACxE,wBAAgB,cAAc,CAAC,KAAK,EAAE,aAAa,GAAG,MAAM,CAwE3D;AAED,kFAAkF;AAClF,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEjD;AAED,8FAA8F;AAC9F,wBAAgB,UAAU,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAEvE;AAED,yFAAyF;AACzF,wBAAsB,cAAc,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAajG;AAED,kFAAkF;AAClF,wBAAsB,cAAc,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC,CAgB7F;AAED,uFAAuF;AACvF,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAWvE;AAED,wBAAsB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAOlE;AAED,4FAA4F;AAC5F,wBAAsB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAG9D;AAED,8FAA8F;AAC9F,wBAAsB,iBAAiB,CAAC,IAAI,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,CAOvE;AAED,wBAAsB,SAAS,CAAC,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAI5F;AAED,gEAAgE;AAChE,wBAAsB,SAAS,CAAC,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAMhF"}
@@ -1,262 +0,0 @@
1
- import { dirname, join, posix, relative } from "node:path"
2
- import { SixbCliError } from "./errors"
3
-
4
- /** The GitHub environment that holds the deploy secrets and gates the deploy job. */
5
- export const CI_ENVIRONMENT = "production"
6
-
7
- /** The secret a private submodule's checkout reads. */
8
- export const SUBMODULE_TOKEN_SECRET = "SIXB_GITHUB_TOKEN"
9
-
10
- /** Actions pinned by commit, so a moved tag cannot change what runs with the deploy key. */
11
- const CHECKOUT = "actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1"
12
- const SETUP_BUN = "oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0"
13
-
14
- export interface GitHubRepo {
15
- /** `owner/name`. */
16
- readonly name: string
17
- readonly defaultBranch: string
18
- }
19
-
20
- export interface Submodule {
21
- readonly path: string
22
- readonly url: string
23
- /** `owner/name` when the submodule lives on GitHub. */
24
- readonly repo: string | null
25
- }
26
-
27
- export interface WorkflowInput {
28
- /** The deployment's name. */
29
- readonly name: string
30
- readonly branch: string
31
- /** The project's directory relative to the repository root, `"."` at the root. */
32
- readonly projectPath: string
33
- /** The `package.json` that pins Bun, relative to the repository root. */
34
- readonly bunVersionFile: string | null
35
- /** GitHub secret names, by the environment variable the install lines read. */
36
- readonly secrets: Readonly<Record<string, string>>
37
- readonly install: readonly string[]
38
- readonly submodules: "none" | "public" | "private"
39
- }
40
-
41
- /** A GitHub Actions workflow that deploys on every push to `branch`. */
42
- export function renderWorkflow(input: WorkflowInput): string {
43
- const workingDirectory =
44
- input.projectPath === "." ? [] : [` working-directory: ${input.projectPath}`]
45
- const checkoutWith = [
46
- " persist-credentials: false",
47
- ...(input.submodules === "none" ? [] : [" submodules: recursive"]),
48
- ...(input.submodules === "private"
49
- ? [` token: \${{ secrets.${SUBMODULE_TOKEN_SECRET} }}`]
50
- : []),
51
- ]
52
- const tokenCheck =
53
- input.submodules === "private"
54
- ? [
55
- " - name: Check the token for private submodules",
56
- " env:",
57
- ` HAS_TOKEN: \${{ secrets.${SUBMODULE_TOKEN_SECRET} != '' }}`,
58
- " run: |",
59
- ' if [ "$HAS_TOKEN" != true ]; then',
60
- ` echo "::error::Set the ${SUBMODULE_TOKEN_SECRET} secret in the ${CI_ENVIRONMENT} environment to a token that can read this repository's private submodules."`,
61
- " exit 1",
62
- " fi",
63
- ]
64
- : []
65
-
66
- return [
67
- `# Written by \`sixb deploy ci\`. Run it again to rotate the deploy key.`,
68
- `name: Deploy ${input.name}`,
69
- "",
70
- "on:",
71
- " push:",
72
- ` branches: [${JSON.stringify(input.branch)}]`,
73
- " workflow_dispatch:",
74
- "",
75
- "permissions:",
76
- " contents: read",
77
- "",
78
- "# One deploy at a time; a push during a deploy waits for it instead of cancelling it.",
79
- "concurrency:",
80
- ` group: sixb-deploy-${input.name}`,
81
- " cancel-in-progress: false",
82
- "",
83
- "jobs:",
84
- " deploy:",
85
- " runs-on: ubuntu-latest",
86
- ` environment: ${CI_ENVIRONMENT}`,
87
- " timeout-minutes: 30",
88
- " steps:",
89
- ...tokenCheck,
90
- ` - uses: ${CHECKOUT}`,
91
- " with:",
92
- ...checkoutWith,
93
- ` - uses: ${SETUP_BUN}`,
94
- ...(input.bunVersionFile
95
- ? [" with:", ` bun-version-file: ${input.bunVersionFile}`]
96
- : []),
97
- " - name: Install dependencies",
98
- // `sixb deploy` only loads `sixb.deploy.ts` and uploads the source; the server installs again
99
- // with lifecycle scripts. Skipping them here skips downloads such as a Playwright browser.
100
- " run: bun install --frozen-lockfile --ignore-scripts",
101
- ...workingDirectory,
102
- " - name: Install the deploy key",
103
- " env:",
104
- ...Object.entries(input.secrets).map(
105
- ([variable, secret]) => ` ${variable}: \${{ secrets.${secret} }}`
106
- ),
107
- " run: |",
108
- ...input.install.map((line) => ` ${line}`),
109
- " - name: Deploy",
110
- " run: bunx sixb deploy",
111
- ...workingDirectory,
112
- "",
113
- ].join("\n")
114
- }
115
-
116
- /** Where the workflow for a deployment lives, relative to the repository root. */
117
- export function workflowPath(name: string): string {
118
- return `.github/workflows/deploy-${name}.yml`
119
- }
120
-
121
- /** The GitHub secret for one of a deployment's variables; a repository may deploy several. */
122
- export function secretName(deployment: string, variable: string): string {
123
- return `${variable}_${deployment.toUpperCase().replaceAll("-", "_")}`
124
- }
125
-
126
- /** The `package.json` that pins Bun for the project, relative to the repository root. */
127
- export async function bunVersionFile(projectDir: string, repoRoot: string): Promise<string | null> {
128
- for (let dir = projectDir; ; dir = dirname(dir)) {
129
- const manifest = await Bun.file(join(dir, "package.json"))
130
- .json()
131
- .catch(() => null)
132
- if (
133
- typeof manifest?.packageManager === "string" &&
134
- manifest.packageManager.startsWith("bun@")
135
- ) {
136
- return relative(repoRoot, join(dir, "package.json")).split("\\").join("/")
137
- }
138
- if (dir === repoRoot || dirname(dir) === dir) return null
139
- }
140
- }
141
-
142
- /** The submodules `.gitmodules` lists, with the GitHub repository behind each. */
143
- export async function readSubmodules(repoRoot: string, repo: GitHubRepo): Promise<Submodule[]> {
144
- const output = await run(
145
- ["git", "config", "--file", ".gitmodules", "--get-regexp", "^submodule\\..*\\.(path|url)$"],
146
- { cwd: repoRoot }
147
- ).catch(() => "")
148
- const byName = new Map<string, { path?: string; url?: string }>()
149
- for (const line of output.split("\n")) {
150
- const match = line.match(/^submodule\.(.+)\.(path|url) (.+)$/)
151
- if (!match?.[1] || !match[2] || !match[3]) continue
152
- const entry = byName.get(match[1]) ?? {}
153
- entry[match[2] as "path" | "url"] = match[3]
154
- byName.set(match[1], entry)
155
- }
156
- return [...byName.values()].flatMap(({ path, url }) =>
157
- path && url ? [{ path, url, repo: githubRepoOf(url, repo.name) }] : []
158
- )
159
- }
160
-
161
- /** `owner/name` for a GitHub remote URL, resolving a relative one against `parent`. */
162
- export function githubRepoOf(url: string, parent: string): string | null {
163
- if (url.startsWith("./") || url.startsWith("../")) {
164
- const resolved = posix.normalize(posix.join(parent, url))
165
- return resolved.replace(/\.git$/, "").split("/").length === 2
166
- ? resolved.replace(/\.git$/, "")
167
- : null
168
- }
169
- const match = url.match(
170
- /^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([^/]+\/[^/]+?)(?:\.git)?\/?$/
171
- )
172
- return match?.[1] ?? null
173
- }
174
-
175
- export async function currentRepo(cwd: string): Promise<GitHubRepo> {
176
- const output = await gh(["repo", "view", "--json", "nameWithOwner,defaultBranchRef"], { cwd })
177
- const parsed = JSON.parse(output) as {
178
- nameWithOwner: string
179
- defaultBranchRef: { name: string } | null
180
- }
181
- return { name: parsed.nameWithOwner, defaultBranch: parsed.defaultBranchRef?.name ?? "main" }
182
- }
183
-
184
- /** Whether CI's own token cannot read `repo`. A repository this login cannot see counts. */
185
- export async function isPrivate(repo: string): Promise<boolean> {
186
- const output = await gh(["api", `repos/${repo}`, "--jq", ".private"]).catch(() => "true")
187
- return output.trim() !== "false"
188
- }
189
-
190
- /** Creates the environment when it is missing. An existing one keeps its protection rules. */
191
- export async function ensureEnvironment(repo: GitHubRepo): Promise<void> {
192
- const path = `repos/${repo.name}/environments/${CI_ENVIRONMENT}`
193
- const exists = await gh(["api", path, "--silent"]).then(
194
- () => true,
195
- () => false
196
- )
197
- if (!exists) await gh(["api", "--method", "PUT", path, "--silent"])
198
- }
199
-
200
- export async function setSecret(repo: GitHubRepo, name: string, value: string): Promise<void> {
201
- await gh(["secret", "set", name, "--env", CI_ENVIRONMENT, "--repo", repo.name], {
202
- input: value,
203
- })
204
- }
205
-
206
- /** Whether the environment or the repository has the secret. */
207
- export async function hasSecret(repo: GitHubRepo, name: string): Promise<boolean> {
208
- for (const scope of [["--env", CI_ENVIRONMENT], []]) {
209
- const list = await gh(["secret", "list", ...scope, "--repo", repo.name, "--json", "name"])
210
- if ((JSON.parse(list) as { name: string }[]).some((secret) => secret.name === name)) return true
211
- }
212
- return false
213
- }
214
-
215
- async function gh(
216
- args: readonly string[],
217
- options: { readonly cwd?: string; readonly input?: string } = {}
218
- ): Promise<string> {
219
- try {
220
- return await run(["gh", ...args], { ...options, env: ghEnvironment() })
221
- } catch (error) {
222
- const reason = error instanceof Error ? error.message : String(error)
223
- throw new SixbCliError(`[SixbDeploy] gh ${args.slice(0, 2).join(" ")} failed: ${reason}`, {
224
- remediation:
225
- "`sixb deploy ci` uses the GitHub CLI. Install it, run `gh auth login`, and make sure " +
226
- "you can change this repository's settings.",
227
- })
228
- }
229
- }
230
-
231
- /**
232
- * Bun loads the project's `.env` into this process, and a connector's `GITHUB_TOKEN` there would
233
- * take precedence over the user's `gh auth login`. `GH_TOKEN` stays: it is gh's explicit override.
234
- */
235
- function ghEnvironment(): Record<string, string | undefined> {
236
- const { GITHUB_TOKEN: _projectToken, ...env } = process.env
237
- return env
238
- }
239
-
240
- async function run(
241
- command: readonly string[],
242
- options: {
243
- readonly cwd?: string
244
- readonly input?: string
245
- readonly env?: Record<string, string | undefined>
246
- }
247
- ): Promise<string> {
248
- const child = Bun.spawn([...command], {
249
- cwd: options.cwd,
250
- ...(options.env === undefined ? {} : { env: options.env }),
251
- stdin: options.input === undefined ? "ignore" : new Blob([options.input]),
252
- stdout: "pipe",
253
- stderr: "pipe",
254
- })
255
- const [exitCode, stdout, stderr] = await Promise.all([
256
- child.exited,
257
- new Response(child.stdout).text(),
258
- new Response(child.stderr).text(),
259
- ])
260
- if (exitCode !== 0) throw new Error(stderr.trim() || `exited with code ${exitCode}`)
261
- return stdout.trim()
262
- }