saasaloy 0.6.0 → 0.7.0

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 (57) hide show
  1. package/README.md +7 -7
  2. package/dist/index.js +3952 -1899
  3. package/dist/index.js.map +1 -1
  4. package/package.json +2 -1
  5. package/schemas/manifest.schema.json +32 -1
  6. package/schemas/registry-item.schema.json +57 -2
  7. package/schemas/saasaloy-lock.schema.json +9 -0
  8. package/schemas/saasaloy.schema.json +12 -0
  9. package/templates/base/AGENTS.md +118 -63
  10. package/templates/base/README.md +16 -1
  11. package/templates/base/_agents/skills/saasaloy-config/SKILL.md +131 -0
  12. package/templates/base/_agents/skills/saasaloy-deploy/SKILL.md +280 -0
  13. package/templates/base/_agents/skills/saasaloy-design/SKILL.md +21 -11
  14. package/templates/base/_agents/skills/saasaloy-env/SKILL.md +8 -7
  15. package/templates/base/_agents/skills/saasaloy-landing-copy/SKILL.md +10 -9
  16. package/templates/base/_agents/skills/saasaloy-setup/SKILL.md +30 -22
  17. package/templates/base/_agents/skills/saasaloy-testing/SKILL.md +85 -0
  18. package/templates/base/_gitignore +4 -0
  19. package/templates/base/_prettierignore +5 -0
  20. package/templates/base/_saasaloy-base.json +6 -2
  21. package/templates/base/apps/web/package.json +1 -0
  22. package/templates/base/apps/web/src/layouts/Layout.astro +2 -1
  23. package/templates/base/apps/web/src/pages/privacy.astro +2 -0
  24. package/templates/base/apps/web/src/pages/terms.astro +2 -0
  25. package/templates/base/docs/runbook-deploy.md +72 -0
  26. package/templates/base/oxlint.config.mjs +62 -0
  27. package/templates/base/package.json +7 -4
  28. package/templates/base/packages/config/package.json +19 -0
  29. package/templates/base/packages/config/src/define.test.ts +134 -0
  30. package/templates/base/packages/config/src/define.ts +135 -0
  31. package/templates/base/packages/config/src/index.ts +34 -0
  32. package/templates/base/packages/config/src/project.ts +25 -0
  33. package/templates/base/packages/config/src/sections/app.ts +27 -0
  34. package/templates/base/packages/config/src/sections.ts +22 -0
  35. package/templates/base/packages/config/tsconfig.json +4 -0
  36. package/templates/base/packages/env/package.json +2 -1
  37. package/templates/base/packages/env/src/deploy.ts +3 -2
  38. package/templates/base/packages/env/src/services.test.ts +27 -11
  39. package/templates/base/packages/tooling/package.json +21 -0
  40. package/templates/base/packages/tooling/src/deploy-production.test.ts +923 -0
  41. package/templates/base/packages/tooling/src/deploy-production.ts +1041 -0
  42. package/templates/base/packages/tooling/src/deploy.config.ts +30 -0
  43. package/templates/base/packages/tooling/src/link-skills.test.ts +126 -0
  44. package/templates/base/packages/tooling/src/link-skills.ts +142 -0
  45. package/templates/base/packages/tooling/src/release.test.ts +205 -0
  46. package/templates/base/packages/tooling/src/release.ts +228 -0
  47. package/templates/base/packages/tooling/src/targets.ts +38 -0
  48. package/templates/base/packages/tooling/src/types.ts +78 -0
  49. package/templates/base/packages/tooling/tsconfig.json +11 -0
  50. package/templates/base/packages/ui/package.json +4 -2
  51. package/templates/base/packages/ui/src/blocks/footer.tsx +5 -3
  52. package/templates/base/packages/ui/src/containers/README.md +6 -5
  53. package/templates/base/packages/ui/src/content/landing.ts +2 -4
  54. package/templates/base/packages/ui/src/index.ts +10 -5
  55. package/templates/base/saasaloy.json +2 -1
  56. package/templates/base/turbo.json +1 -5
  57. package/templates/base/vitest.config.ts +5 -1
@@ -0,0 +1,923 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import {
3
+ ciState,
4
+ deployProduction,
5
+ gateProblems,
6
+ gateReport,
7
+ orderTargets,
8
+ parseArgs,
9
+ releaseLabel,
10
+ releaseWarning,
11
+ resolveConfig,
12
+ smokeProblem,
13
+ smokeRowProblems,
14
+ smokeUrls,
15
+ tagMessage,
16
+ tagName,
17
+ } from "./deploy-production.ts";
18
+ import type {
19
+ Facts,
20
+ Io,
21
+ Options,
22
+ ReleaseFacts,
23
+ SmokeRequest,
24
+ Workspace,
25
+ } from "./deploy-production.ts";
26
+ import type { DeployTarget, SmokeCheck } from "./types.ts";
27
+
28
+ const HEAD = "7812604aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
29
+ const config = resolveConfig({});
30
+ const withCi = resolveConfig({ ciWorkflow: "ci.yml" });
31
+
32
+ function facts(overrides: Partial<Facts> = {}): Facts {
33
+ return {
34
+ branch: "main",
35
+ dirty: [],
36
+ head: HEAD,
37
+ remoteHead: HEAD,
38
+ ci: "passed",
39
+ lastTag: "deploy-20261023-1430",
40
+ newMigrations: [],
41
+ hasDb: true,
42
+ release: {
43
+ onHead: "v0.3.0",
44
+ latest: "v0.3.0",
45
+ after: [],
46
+ sinceDeploy: true,
47
+ },
48
+ ...overrides,
49
+ };
50
+ }
51
+
52
+ const plain: Options = { dryRun: false, migrate: false };
53
+
54
+ describe(parseArgs, () => {
55
+ it("takes no flags as a plain deploy", () => {
56
+ expect(parseArgs([])).toStrictEqual(plain);
57
+ });
58
+
59
+ it("reads every flag", () => {
60
+ expect(
61
+ parseArgs([
62
+ "--dry-run",
63
+ "--migrate",
64
+ "--skip-ci",
65
+ "Actions outage",
66
+ "--only",
67
+ "api",
68
+ ])
69
+ ).toStrictEqual({
70
+ dryRun: true,
71
+ migrate: true,
72
+ skipCi: "Actions outage",
73
+ only: "api",
74
+ });
75
+ });
76
+
77
+ it("ignores the -- pnpm passes through", () => {
78
+ expect(parseArgs(["--", "--dry-run"])).toStrictEqual({
79
+ ...plain,
80
+ dryRun: true,
81
+ });
82
+ });
83
+
84
+ it("refuses --skip-ci without a reason", () => {
85
+ expect(() => parseArgs(["--skip-ci"])).toThrow(/needs a reason/);
86
+ expect(() => parseArgs(["--skip-ci", "--migrate"])).toThrow(
87
+ /needs a reason/
88
+ );
89
+ expect(() => parseArgs(["--skip-ci", " "])).toThrow(/needs a reason/);
90
+ });
91
+
92
+ it("refuses --only without a service", () => {
93
+ expect(() => parseArgs(["--only"])).toThrow(/--only needs a service/);
94
+ expect(() => parseArgs(["--only", "--dry-run"])).toThrow(
95
+ /--only needs a service/
96
+ );
97
+ });
98
+
99
+ it("refuses an unknown flag", () => {
100
+ expect(() => parseArgs(["--force"])).toThrow(/Unknown argument --force/);
101
+ });
102
+ });
103
+
104
+ describe(ciState, () => {
105
+ it("passes when any run on the commit succeeded", () => {
106
+ expect(
107
+ ciState([
108
+ { status: "completed", conclusion: "cancelled" },
109
+ { status: "completed", conclusion: "success" },
110
+ ])
111
+ ).toBe("passed");
112
+ });
113
+
114
+ it("waits while a run is not complete", () => {
115
+ expect(ciState([{ status: "in_progress", conclusion: "" }])).toBe(
116
+ "running"
117
+ );
118
+ });
119
+
120
+ it("fails when every run finished without success", () => {
121
+ expect(ciState([{ status: "completed", conclusion: "failure" }])).toBe(
122
+ "failed"
123
+ );
124
+ });
125
+
126
+ it("reports no run", () => {
127
+ expect(ciState([])).toBe("missing");
128
+ });
129
+ });
130
+
131
+ describe(resolveConfig, () => {
132
+ it("fills every key an older or emptied config file lacks", () => {
133
+ expect(resolveConfig({})).toStrictEqual({
134
+ branches: ["main", "hotfix-*"],
135
+ tagPrefix: "deploy-",
136
+ ciWorkflow: undefined,
137
+ migrations: "packages/db/migrations/*.sql",
138
+ release: {
139
+ tagPrefix: "v",
140
+ githubRelease: true,
141
+ preMajor: true,
142
+ changelogSections: undefined,
143
+ },
144
+ });
145
+ });
146
+
147
+ it("keeps what the project set", () => {
148
+ expect(
149
+ resolveConfig({ branches: ["release"], ciWorkflow: "ci.yml" })
150
+ ).toMatchObject({ branches: ["release"], ciWorkflow: "ci.yml" });
151
+ });
152
+ });
153
+
154
+ describe(gateProblems, () => {
155
+ it("passes main at its pushed HEAD", () => {
156
+ expect(gateProblems(facts(), plain, config)).toStrictEqual([]);
157
+ });
158
+
159
+ it("passes a hotfix branch", () => {
160
+ expect(
161
+ gateProblems(facts({ branch: "hotfix-prices" }), plain, config)
162
+ ).toStrictEqual([]);
163
+ });
164
+
165
+ it("refuses a feature branch and names the allowed ones", () => {
166
+ const [problem] = gateProblems(
167
+ facts({ branch: "issue-80-admin" }),
168
+ plain,
169
+ config
170
+ );
171
+ expect(problem).toMatch(/The branch is issue-80-admin/);
172
+ expect(problem).toMatch(/main, hotfix-\*/);
173
+ expect(problem).toMatch(/git switch main/);
174
+ });
175
+
176
+ it("reads the branch list from the config", () => {
177
+ const release = resolveConfig({ branches: ["release"] });
178
+ expect(gateProblems(facts(), plain, release)).toHaveLength(1);
179
+ expect(
180
+ gateProblems(facts({ branch: "release" }), plain, release)
181
+ ).toStrictEqual([]);
182
+ });
183
+
184
+ it("refuses a dirty tree and names the files", () => {
185
+ const [problem] = gateProblems(
186
+ facts({ dirty: ["README.md"] }),
187
+ plain,
188
+ config
189
+ );
190
+ expect(problem).toMatch(/uncommitted changes \(README.md\)/);
191
+ expect(problem).toMatch(/git commit/);
192
+ });
193
+
194
+ it("refuses a branch origin does not have", () => {
195
+ const [problem] = gateProblems(
196
+ facts({ branch: "hotfix-prices", remoteHead: undefined }),
197
+ plain,
198
+ config
199
+ );
200
+ expect(problem).toMatch(/git push -u origin hotfix-prices/);
201
+ });
202
+
203
+ it("refuses a HEAD that differs from origin", () => {
204
+ const [problem] = gateProblems(
205
+ facts({ remoteHead: "1234567bbb" }),
206
+ plain,
207
+ config
208
+ );
209
+ expect(problem).toMatch(/HEAD \(7812604\) is not origin\/main \(1234567\)/);
210
+ });
211
+
212
+ it.each(["failed", "running", "missing"] as const)(
213
+ "refuses CI that is %s, and names --skip-ci",
214
+ (ci) => {
215
+ const [problem] = gateProblems(facts({ ci }), plain, withCi);
216
+ expect(problem).toMatch(/ci\.yml/);
217
+ expect(problem).toMatch(/--skip-ci/);
218
+ }
219
+ );
220
+
221
+ it("lets --skip-ci pass a red CI", () => {
222
+ expect(
223
+ gateProblems(
224
+ facts({ ci: "failed" }),
225
+ { ...plain, skipCi: "outage" },
226
+ withCi
227
+ )
228
+ ).toStrictEqual([]);
229
+ });
230
+
231
+ it("asks for --migrate when a migration changed", () => {
232
+ const changed = facts({
233
+ newMigrations: ["packages/db/migrations/0012_orders.sql"],
234
+ });
235
+ const [problem] = gateProblems(changed, plain, config);
236
+ expect(problem).toMatch(
237
+ /1 migration file\(s\) changed since deploy-20261023-1430/
238
+ );
239
+ expect(problem).toMatch(/pnpm deploy:production --migrate/);
240
+ expect(
241
+ gateProblems(changed, { ...plain, migrate: true }, config)
242
+ ).toStrictEqual([]);
243
+ });
244
+
245
+ it("asks for --migrate on a one-Worker deploy too", () => {
246
+ const changed = facts({ newMigrations: ["packages/db/migrations/x.sql"] });
247
+ expect(
248
+ gateProblems(changed, { ...plain, only: "api" }, config)
249
+ ).toHaveLength(1);
250
+ });
251
+
252
+ it("names the first commit when there is no deploy tag", () => {
253
+ const [problem] = gateProblems(
254
+ facts({ lastTag: undefined, newMigrations: ["a.sql"] }),
255
+ plain,
256
+ config
257
+ );
258
+ expect(problem).toMatch(/since the first commit \(no deploy tag yet\)/);
259
+ });
260
+
261
+ it("refuses --migrate in a project with no @repo/db", () => {
262
+ const [problem] = gateProblems(
263
+ facts({ hasDb: false }),
264
+ { ...plain, migrate: true },
265
+ config
266
+ );
267
+ expect(problem).toMatch(/--migrate needs the @repo\/db workspace/);
268
+ });
269
+
270
+ it("lists every failed gate at once", () => {
271
+ expect(
272
+ gateProblems(
273
+ facts({
274
+ branch: "x",
275
+ dirty: ["a"],
276
+ ci: "failed",
277
+ newMigrations: ["b"],
278
+ }),
279
+ plain,
280
+ withCi
281
+ )
282
+ ).toHaveLength(4);
283
+ });
284
+ });
285
+
286
+ describe(gateReport, () => {
287
+ it("reports the CI gate as off when the config names no workflow", () => {
288
+ const ci = gateReport(facts({ ci: "off" }), plain, config).find(
289
+ (gate) => gate.name === "CI"
290
+ );
291
+ expect(ci).toMatchObject({ state: "off" });
292
+ expect(ci?.detail).toMatch(/CI gate: off/);
293
+ });
294
+
295
+ it("reports a passed gate as ok", () => {
296
+ const states = gateReport(facts(), plain, withCi).map((gate) => gate.state);
297
+ expect(states.every((state) => state === "ok")).toBeTruthy();
298
+ });
299
+ });
300
+
301
+ describe(tagName, () => {
302
+ it("writes the UTC date and minute", () => {
303
+ expect(tagName(new Date("2026-10-23T14:30:59Z"), "deploy-")).toBe(
304
+ "deploy-20261023-1430"
305
+ );
306
+ });
307
+
308
+ it("uses the configured prefix", () => {
309
+ expect(tagName(new Date("2026-10-23T14:30:59Z"), "live-")).toBe(
310
+ "live-20261023-1430"
311
+ );
312
+ });
313
+ });
314
+
315
+ describe(tagMessage, () => {
316
+ it("records the commit, the Workers, and the migration and CI skip when they happened", () => {
317
+ const message = tagMessage(
318
+ HEAD,
319
+ { ...plain, migrate: true, skipCi: "Actions outage" },
320
+ ["api", "web"],
321
+ "v0.3.0"
322
+ );
323
+ expect(message).toMatch(
324
+ /Production deploy of 7812604 \(v0\.3\.0\): api, web\./
325
+ );
326
+ expect(message).toMatch(
327
+ /Ran pnpm --filter @repo\/db run db:prod:migrate first/
328
+ );
329
+ expect(message).toMatch(/CI gate skipped: Actions outage/);
330
+ });
331
+
332
+ it("leaves out what did not happen", () => {
333
+ const message = tagMessage(HEAD, plain, ["web"], "v0.3.0");
334
+ expect(message).not.toMatch(/migrate|skipped/);
335
+ });
336
+ });
337
+
338
+ const noRelease: ReleaseFacts = { after: [], sinceDeploy: false };
339
+ const pastRelease: ReleaseFacts = {
340
+ latest: "v0.3.0",
341
+ after: [
342
+ "abc1234 fix(api): retry the webhook",
343
+ "def5678 feat(web): add the faq",
344
+ ],
345
+ sinceDeploy: true,
346
+ };
347
+
348
+ describe(releaseLabel, () => {
349
+ it("names the release tag on HEAD", () => {
350
+ expect(releaseLabel(facts().release)).toBe("v0.3.0");
351
+ });
352
+
353
+ it("says how far HEAD is past the newest release", () => {
354
+ expect(releaseLabel(pastRelease)).toBe("2 commit(s) after v0.3.0");
355
+ });
356
+
357
+ it("says when no release exists", () => {
358
+ expect(releaseLabel(noRelease)).toBe("no release tag");
359
+ });
360
+ });
361
+
362
+ describe(releaseWarning, () => {
363
+ it("is silent when HEAD is a release commit", () => {
364
+ expect(
365
+ releaseWarning(facts().release, "deploy-20261023-1430")
366
+ ).toBeUndefined();
367
+ });
368
+
369
+ it("names a project with no release yet", () => {
370
+ expect(releaseWarning(noRelease)).toMatch(
371
+ /HEAD has no release tag yet.*run pnpm release first, unless this is an urgent hotfix/
372
+ );
373
+ });
374
+
375
+ it("lists the commits after the release, so the changelog gap is visible", () => {
376
+ const warning = releaseWarning(pastRelease, "deploy-20261023-1430") ?? "";
377
+ expect(warning).toMatch(/HEAD is 2 commit\(s\) past v0\.3\.0/);
378
+ expect(warning).toMatch(/\n {2}abc1234 fix\(api\): retry the webhook/);
379
+ expect(warning).toMatch(/\n {2}def5678 feat\(web\): add the faq/);
380
+ });
381
+
382
+ it("names the last deploy tag when no release came after it", () => {
383
+ expect(
384
+ releaseWarning(
385
+ { ...pastRelease, sinceDeploy: false },
386
+ "deploy-20261023-1430"
387
+ )
388
+ ).toMatch(/No release since the last deploy tag \(deploy-20261023-1430\)/);
389
+ });
390
+ });
391
+
392
+ describe(smokeProblem, () => {
393
+ const api: SmokeRequest = {
394
+ id: "api-health",
395
+ service: "api",
396
+ path: "/health",
397
+ status: 200,
398
+ body: '"ok"',
399
+ url: "https://api.example.com/health",
400
+ };
401
+
402
+ it("passes the right status and body", () => {
403
+ expect(smokeProblem(api, 200, '{"status":"ok"}')).toBeUndefined();
404
+ });
405
+
406
+ it("fails a wrong status", () => {
407
+ expect(smokeProblem(api, 500, "")).toMatch(
408
+ /https:\/\/api\.example\.com\/health answered 500, expected 200/
409
+ );
410
+ });
411
+
412
+ it("fails a right status with the wrong body", () => {
413
+ expect(smokeProblem(api, 200, "Not Found")).toMatch(/without "ok"/);
414
+ });
415
+ });
416
+
417
+ describe(orderTargets, () => {
418
+ const targets: DeployTarget[] = [
419
+ { service: "web", order: 30 },
420
+ { service: "api", order: 10 },
421
+ { service: "admin", order: 20 },
422
+ ];
423
+
424
+ it("orders the installed Workers, lowest first", () => {
425
+ expect(orderTargets(targets, ["web", "admin", "api"])).toStrictEqual({
426
+ order: ["api", "admin", "web"],
427
+ problems: [],
428
+ });
429
+ });
430
+
431
+ it("breaks a tie by service name, so the order never depends on file order", () => {
432
+ const tied = orderTargets(
433
+ [
434
+ { service: "web", order: 10 },
435
+ { service: "docs", order: 10 },
436
+ ],
437
+ ["web", "docs"]
438
+ );
439
+ expect(tied.order).toStrictEqual(["docs", "web"]);
440
+ });
441
+
442
+ it("stops on a deployable workspace with no row, and names it", () => {
443
+ const { problems } = orderTargets(
444
+ [{ service: "web", order: 30 }],
445
+ ["web", "api"]
446
+ );
447
+ expect(problems).toHaveLength(1);
448
+ expect(problems[0]).toMatch(
449
+ /apps\/api deploys and has no DEPLOY_TARGETS row/
450
+ );
451
+ expect(problems[0]).toMatch(/packages\/tooling\/src\/targets\.ts/);
452
+ });
453
+
454
+ it("stops on a row for a service that is not a deployable workspace", () => {
455
+ const { problems } = orderTargets(targets, ["web"]);
456
+ expect(problems).toHaveLength(2);
457
+ expect(problems.join("\n")).toMatch(/DEPLOY_TARGETS names api/);
458
+ expect(problems.join("\n")).toMatch(/DEPLOY_TARGETS names admin/);
459
+ });
460
+
461
+ it("stops on a service listed twice", () => {
462
+ const { problems } = orderTargets(
463
+ [
464
+ { service: "web", order: 30 },
465
+ { service: "web", order: 40 },
466
+ ],
467
+ ["web"]
468
+ );
469
+ expect(problems.join("\n")).toMatch(/DEPLOY_TARGETS lists web twice/);
470
+ });
471
+ });
472
+
473
+ describe(smokeRowProblems, () => {
474
+ it("stops on a row for a service that does not deploy", () => {
475
+ const problems = smokeRowProblems(
476
+ [{ id: "api-health", service: "api", path: "/health", status: 200 }],
477
+ ["web"]
478
+ );
479
+ expect(problems.join("\n")).toMatch(
480
+ /SMOKE_CHECKS row api-health names api/
481
+ );
482
+ });
483
+
484
+ it("stops on an id listed twice", () => {
485
+ const row: SmokeCheck = {
486
+ id: "home",
487
+ service: "web",
488
+ path: "/",
489
+ status: 200,
490
+ };
491
+ expect(smokeRowProblems([row, row], ["web"]).join("\n")).toMatch(
492
+ /SMOKE_CHECKS lists home twice/
493
+ );
494
+ });
495
+ });
496
+
497
+ describe(smokeUrls, () => {
498
+ const checks: SmokeCheck[] = [
499
+ { id: "web-home", service: "web", path: "/", status: 200 },
500
+ { id: "web-404", service: "web", path: "/nope", status: 404 },
501
+ { id: "api-health", service: "api", path: "/health", status: 200 },
502
+ ];
503
+
504
+ it("builds one request per custom domain and check of the service", () => {
505
+ const urls = smokeUrls(
506
+ "web",
507
+ {
508
+ routes: [
509
+ { pattern: "example.com", custom_domain: true },
510
+ { pattern: "www.example.com", custom_domain: true },
511
+ ],
512
+ },
513
+ checks
514
+ ).map((request) => request.url);
515
+ expect(urls).toStrictEqual([
516
+ "https://example.com/",
517
+ "https://example.com/nope",
518
+ "https://www.example.com/",
519
+ "https://www.example.com/nope",
520
+ ]);
521
+ });
522
+
523
+ it("ignores a zone route and a route string, which are not custom domains", () => {
524
+ expect(
525
+ smokeUrls(
526
+ "web",
527
+ {
528
+ routes: [
529
+ "example.com/*",
530
+ { pattern: "example.com/*", zone_name: "example.com" },
531
+ ],
532
+ },
533
+ checks
534
+ )
535
+ ).toStrictEqual([]);
536
+ });
537
+
538
+ it("answers nothing for a config with no routes", () => {
539
+ expect(smokeUrls("api", { name: "x-api" }, checks)).toStrictEqual([]);
540
+ expect(smokeUrls("api", undefined, checks)).toStrictEqual([]);
541
+ });
542
+ });
543
+
544
+ // ---- The whole run, with every side effect faked -----------------------------------------
545
+
546
+ interface Fake {
547
+ io: Io;
548
+ said: string[];
549
+ runs: string[];
550
+ gits: string[];
551
+ }
552
+
553
+ interface FakeSetup {
554
+ branch?: string;
555
+ dirty?: string;
556
+ remoteHead?: string | undefined;
557
+ lastTag?: string | undefined;
558
+ migrations?: string;
559
+ workspaces?: Workspace[];
560
+ routes?: Record<string, unknown>;
561
+ hasDb?: boolean;
562
+ runExit?: (line: string) => number;
563
+ answer?: (url: string) => { status: number; body: string };
564
+ pushFails?: boolean;
565
+ noCommit?: boolean;
566
+ /** The release tag on HEAD. */
567
+ releaseOnHead?: string;
568
+ /** The newest release tag HEAD descends from, when HEAD is not one. */
569
+ latestRelease?: string;
570
+ /** `git log --oneline <latestRelease>..HEAD`. */
571
+ afterRelease?: string;
572
+ /** Whether the last deploy tag already contains `latestRelease`. */
573
+ releaseDeployed?: boolean;
574
+ }
575
+
576
+ const WEB: Workspace = { service: "web", packageName: "@repo/web" };
577
+ const API: Workspace = { service: "api", packageName: "@repo/api" };
578
+
579
+ function fake(setup: FakeSetup = {}): Fake {
580
+ const said: string[] = [];
581
+ const runs: string[] = [];
582
+ const gits: string[] = [];
583
+ const remoteHead = "remoteHead" in setup ? setup.remoteHead : HEAD;
584
+ const lastTag = "lastTag" in setup ? setup.lastTag : "deploy-20261020-0900";
585
+ const io: Io = {
586
+ git(args) {
587
+ const line = args.join(" ");
588
+ gits.push(line);
589
+ if (setup.noCommit === true && line.startsWith("rev-parse")) {
590
+ throw new Error("fatal: ambiguous argument 'HEAD': unknown revision");
591
+ }
592
+ if (line === "rev-parse --abbrev-ref HEAD") {
593
+ return setup.branch ?? "main";
594
+ }
595
+ if (line === "rev-parse HEAD") {
596
+ return HEAD;
597
+ }
598
+ if (line.startsWith("rev-parse --verify origin/")) {
599
+ if (remoteHead === undefined) {
600
+ throw new Error("unknown revision");
601
+ }
602
+ return remoteHead;
603
+ }
604
+ if (line.startsWith("status --porcelain")) {
605
+ return setup.dirty ?? "";
606
+ }
607
+ if (line.startsWith("describe") && line.includes("--match v*")) {
608
+ const tag = line.includes("--exact-match")
609
+ ? setup.releaseOnHead
610
+ : (setup.releaseOnHead ?? setup.latestRelease);
611
+ if (tag === undefined) {
612
+ throw new Error("no names found");
613
+ }
614
+ return tag;
615
+ }
616
+ if (line.startsWith("merge-base --is-ancestor")) {
617
+ if (setup.releaseDeployed !== true) {
618
+ throw new Error("not an ancestor");
619
+ }
620
+ return "";
621
+ }
622
+ if (line.startsWith("log --oneline v")) {
623
+ return setup.afterRelease ?? "";
624
+ }
625
+ if (line.startsWith("describe")) {
626
+ if (lastTag === undefined) {
627
+ throw new Error("no names found");
628
+ }
629
+ return lastTag;
630
+ }
631
+ if (line.startsWith("diff --name-only") || line.startsWith("ls-files")) {
632
+ return setup.migrations ?? "";
633
+ }
634
+ if (line.startsWith("push") && setup.pushFails === true) {
635
+ throw new Error("push rejected");
636
+ }
637
+ return "";
638
+ },
639
+ gh: () => "[]",
640
+ run: async (command, args) => {
641
+ const line = [command, ...args].join(" ");
642
+ runs.push(line);
643
+ return await Promise.resolve(setup.runExit?.(line) ?? 0);
644
+ },
645
+ fetch: async (url) => {
646
+ const { status, body } = setup.answer?.(url) ?? { status: 200, body: "" };
647
+ return await Promise.resolve({
648
+ status,
649
+ text: async () => await Promise.resolve(body),
650
+ });
651
+ },
652
+ sleep: async () => {
653
+ await Promise.resolve();
654
+ },
655
+ say: (text) => {
656
+ said.push(text);
657
+ },
658
+ now: () => new Date("2026-10-23T14:30:00Z"),
659
+ workspaces: () => setup.workspaces ?? [WEB],
660
+ wranglerConfig: (service) => setup.routes?.[service],
661
+ hasDb: () => setup.hasDb ?? false,
662
+ };
663
+ return { io, said, runs, gits };
664
+ }
665
+
666
+ const webDomain = {
667
+ web: { routes: [{ pattern: "example.com", custom_domain: true }] },
668
+ };
669
+
670
+ const project = {
671
+ config: {},
672
+ targets: [
673
+ { service: "web", order: 30 },
674
+ { service: "api", order: 10 },
675
+ ],
676
+ smokeChecks: [
677
+ { id: "web-home", service: "web", path: "/", status: 200 },
678
+ { id: "api-health", service: "api", path: "/health", status: 200 },
679
+ ],
680
+ };
681
+
682
+ describe(deployProduction, () => {
683
+ it("runs the env check, each Worker in order, the smoke checks, then tags", async () => {
684
+ const run = fake({
685
+ workspaces: [WEB, API],
686
+ routes: webDomain,
687
+ releaseOnHead: "v0.3.0",
688
+ });
689
+ await deployProduction(plain, run.io, project);
690
+ expect(run.runs).toStrictEqual([
691
+ "node packages/env/src/deploy.ts --check",
692
+ "pnpm --filter @repo/api run deploy",
693
+ "pnpm --filter @repo/web run deploy",
694
+ ]);
695
+ expect(run.gits).toContain(
696
+ "tag --annotate deploy-20261023-1430 --message Production deploy of 7812604 (v0.3.0): api, web."
697
+ );
698
+ expect(run.gits).toContain("push --quiet origin deploy-20261023-1430");
699
+ expect(run.said.join("\n")).toMatch(/api has no custom domain/);
700
+ });
701
+
702
+ it("names the release on HEAD, and prints no release warning", async () => {
703
+ const run = fake({
704
+ workspaces: [WEB, API],
705
+ routes: webDomain,
706
+ releaseOnHead: "v0.3.0",
707
+ });
708
+ await deployProduction(plain, run.io, project);
709
+ const output = run.said.join("\n");
710
+ expect(output).toMatch(/Branch main at 7812604 \(v0\.3\.0\)\./);
711
+ expect(output).toMatch(/Deployed 7812604 \(v0\.3\.0\) and pushed/);
712
+ expect(output).not.toMatch(/Warning:/);
713
+ });
714
+
715
+ it("warns, lists the commits past the release, and still deploys and tags", async () => {
716
+ const run = fake({
717
+ workspaces: [WEB, API],
718
+ routes: webDomain,
719
+ latestRelease: "v0.3.0",
720
+ afterRelease: "abc1234 fix(api): retry the webhook",
721
+ });
722
+ await deployProduction(plain, run.io, project);
723
+ const output = run.said.join("\n");
724
+ expect(output).toMatch(/Warning: HEAD is 1 commit\(s\) past v0\.3\.0/);
725
+ expect(output).toMatch(/abc1234 fix\(api\): retry the webhook/);
726
+ expect(run.gits).toContain(
727
+ "tag --annotate deploy-20261023-1430 --message Production deploy of 7812604 (1 commit(s) after v0.3.0): api, web."
728
+ );
729
+ });
730
+
731
+ it("warns in a dry run when no release exists yet", async () => {
732
+ const run = fake({ workspaces: [WEB, API], routes: webDomain });
733
+ await deployProduction({ ...plain, dryRun: true }, run.io, project);
734
+ expect(run.said.join("\n")).toMatch(/Warning: HEAD has no release tag yet/);
735
+ expect(run.gits.some((line) => line.startsWith("tag"))).toBeFalsy();
736
+ });
737
+
738
+ it.each([false, true])(
739
+ "stops with the fix, not a raw git error, in a repository with no commit (dry run: %s)",
740
+ async (preview) => {
741
+ const run = fake({ noCommit: true, workspaces: [WEB, API] });
742
+ const thrown = await deployProduction(
743
+ { ...plain, dryRun: preview },
744
+ run.io,
745
+ project
746
+ ).catch((error: unknown) => error);
747
+
748
+ expect(thrown).toBeInstanceOf(Error);
749
+ expect(String(thrown)).toMatch(/has no commit yet/);
750
+ expect(String(thrown)).toMatch(/Run: git add -A && git commit/);
751
+ expect(String(thrown)).not.toMatch(/ambiguous argument/);
752
+ expect(run.runs).toStrictEqual([]);
753
+ }
754
+ );
755
+
756
+ async function dryRun(): Promise<Fake> {
757
+ const run = fake({
758
+ branch: "issue-1",
759
+ workspaces: [WEB, API],
760
+ routes: webDomain,
761
+ migrations: "packages/db/migrations/0001_init.sql",
762
+ hasDb: true,
763
+ });
764
+ await deployProduction(
765
+ { ...plain, dryRun: true, migrate: true },
766
+ run.io,
767
+ project
768
+ );
769
+ return run;
770
+ }
771
+
772
+ it("reports every gate, the order and the smoke checks in a dry run", async () => {
773
+ const run = await dryRun();
774
+ const output = run.said.join("\n");
775
+ expect(output).toMatch(/CI gate: off/);
776
+ expect(output).toMatch(/The branch is issue-1/);
777
+ expect(output).toMatch(/api \(10\), web \(30\)/);
778
+ expect(output).toMatch(/https:\/\/example\.com\/ answers 200/);
779
+ expect(output).toMatch(/db:prod:migrate/);
780
+ });
781
+
782
+ it("runs no build, upload, migration or tag in a dry run", async () => {
783
+ const run = await dryRun();
784
+ expect(run.runs).toStrictEqual(["node packages/env/src/deploy.ts --check"]);
785
+ expect(run.gits.some((line) => line.startsWith("tag"))).toBeFalsy();
786
+ });
787
+
788
+ it("stops a real run on a failed gate before anything builds, and names each fix", async () => {
789
+ const run = fake({ dirty: " M README.md", remoteHead: undefined });
790
+ await expect(
791
+ deployProduction(plain, run.io, {
792
+ config: {},
793
+ targets: [{ service: "web", order: 30 }],
794
+ smokeChecks: [],
795
+ })
796
+ ).rejects.toThrow(
797
+ /The deploy did not start[\s\S]*git commit[\s\S]*git push -u origin main/
798
+ );
799
+ expect(run.runs).toStrictEqual([]);
800
+ });
801
+
802
+ it.each([
803
+ [" M AGENTS.md\n?? notes.txt", "AGENTS.md, notes.txt"],
804
+ ["M AGENTS.md\n?? notes.txt", "AGENTS.md, notes.txt"],
805
+ ["R old.md -> new.md", "old.md -> new.md"],
806
+ ])(
807
+ "names each dirty file whole from git status output %j",
808
+ async (porcelain, named) => {
809
+ const run = fake({ dirty: porcelain });
810
+ await expect(
811
+ deployProduction(plain, run.io, {
812
+ config: {},
813
+ targets: [{ service: "web", order: 30 }],
814
+ smokeChecks: [],
815
+ })
816
+ ).rejects.toThrow(`uncommitted changes (${named})`);
817
+ }
818
+ );
819
+
820
+ it("stops before anything builds when a deployable workspace has no row", async () => {
821
+ const run = fake({ workspaces: [WEB, API] });
822
+ await expect(
823
+ deployProduction(plain, run.io, {
824
+ config: {},
825
+ targets: [{ service: "web", order: 30 }],
826
+ smokeChecks: [],
827
+ })
828
+ ).rejects.toThrow(/apps\/api deploys and has no DEPLOY_TARGETS row/);
829
+ expect(run.runs).toStrictEqual([]);
830
+ });
831
+
832
+ it("runs the migration with --migrate, before the first Worker", async () => {
833
+ const run = fake({
834
+ migrations: "packages/db/migrations/0002.sql",
835
+ hasDb: true,
836
+ routes: webDomain,
837
+ });
838
+ await deployProduction({ ...plain, migrate: true }, run.io, {
839
+ config: {},
840
+ targets: [{ service: "web", order: 30 }],
841
+ smokeChecks: [],
842
+ });
843
+ expect(run.runs).toStrictEqual([
844
+ "node packages/env/src/deploy.ts --check",
845
+ "pnpm --filter @repo/db run db:prod:migrate",
846
+ "pnpm --filter @repo/web run deploy",
847
+ ]);
848
+ });
849
+
850
+ it("writes no tag when a smoke check fails, and prints a rollback per Worker", async () => {
851
+ const run = fake({
852
+ workspaces: [WEB, API],
853
+ routes: webDomain,
854
+ answer: () => ({ status: 500, body: "" }),
855
+ });
856
+ await expect(deployProduction(plain, run.io, project)).rejects.toThrow(
857
+ /No deploy tag was written[\s\S]*pnpm --filter @repo\/api exec env-deploy --run api -- wrangler rollback[\s\S]*pnpm --filter @repo\/web exec env-deploy --run web -- wrangler rollback/
858
+ );
859
+ expect(run.gits.some((line) => line.startsWith("tag"))).toBeFalsy();
860
+ });
861
+
862
+ it("tries a failing smoke check three times", async () => {
863
+ let calls = 0;
864
+ const run = fake({
865
+ routes: webDomain,
866
+ answer: () => {
867
+ calls += 1;
868
+ return { status: calls < 3 ? 503 : 200, body: "" };
869
+ },
870
+ });
871
+ await deployProduction(plain, run.io, {
872
+ config: {},
873
+ targets: [{ service: "web", order: 30 }],
874
+ smokeChecks: [{ id: "web-home", service: "web", path: "/", status: 200 }],
875
+ });
876
+ expect(calls).toBe(3);
877
+ });
878
+
879
+ it("keeps the tag local and prints the push when the push fails", async () => {
880
+ const run = fake({ routes: webDomain, pushFails: true });
881
+ await expect(
882
+ deployProduction(plain, run.io, {
883
+ config: {},
884
+ targets: [{ service: "web", order: 30 }],
885
+ smokeChecks: [],
886
+ })
887
+ ).rejects.toThrow(/git push origin deploy-20261023-1430/);
888
+ });
889
+
890
+ it("deploys one Worker with --only, smoke checks it, and writes no tag", async () => {
891
+ const run = fake({ workspaces: [WEB, API], routes: webDomain });
892
+ await deployProduction({ ...plain, only: "web" }, run.io, project);
893
+ expect(run.runs).toStrictEqual([
894
+ "node packages/env/src/deploy.ts --check",
895
+ "pnpm --filter @repo/web run deploy",
896
+ ]);
897
+ expect(run.gits.some((line) => line.startsWith("tag"))).toBeFalsy();
898
+ });
899
+
900
+ it("refuses --only for a service that does not deploy", async () => {
901
+ const run = fake();
902
+ await expect(
903
+ deployProduction({ ...plain, only: "docs" }, run.io, {
904
+ config: {},
905
+ targets: [{ service: "web", order: 30 }],
906
+ smokeChecks: [],
907
+ })
908
+ ).rejects.toThrow(/--only docs is not a deploy target\. Choose web/);
909
+ expect(run.runs).toStrictEqual([]);
910
+ });
911
+
912
+ it("stops when a Worker deploy fails, before the next one and with no tag", async () => {
913
+ const run = fake({
914
+ workspaces: [WEB, API],
915
+ runExit: (line) => (line.includes("@repo/api") ? 1 : 0),
916
+ });
917
+ await expect(deployProduction(plain, run.io, project)).rejects.toThrow(
918
+ /Deploy api failed/
919
+ );
920
+ expect(run.runs).not.toContain("pnpm --filter @repo/web run deploy");
921
+ expect(run.gits.some((line) => line.startsWith("tag"))).toBeFalsy();
922
+ });
923
+ });