@ultimat3/cli 31.26.0 → 31.28.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 (206) hide show
  1. package/CLAUDE.md +47 -37
  2. package/README.md +19 -8
  3. package/package.json +29 -29
  4. package/src/app-manifest.ts +6 -1
  5. package/src/app-mcp.ts +17 -3
  6. package/src/cmd-cache-spec.ts +5 -2
  7. package/src/cmd-db-spec.ts +2 -3
  8. package/src/cmd-db.ts +0 -2
  9. package/src/cmd-deploy-verify-sample.ts +93 -0
  10. package/src/cmd-deploy-verify.ts +2 -41
  11. package/src/cmd-dev-spec.ts +15 -1
  12. package/src/cmd-dev.ts +31 -4
  13. package/src/cmd-doctor.ts +15 -4
  14. package/src/cmd-exercise-spec.ts +7 -1
  15. package/src/cmd-exercise.ts +22 -10
  16. package/src/cmd-generate.ts +2 -0
  17. package/src/cmd-jobs-spec.ts +3 -6
  18. package/src/cmd-jobs.ts +1 -7
  19. package/src/cmd-logs-spec.ts +2 -1
  20. package/src/cmd-logs.ts +9 -28
  21. package/src/cmd-planned.ts +11 -45
  22. package/src/cmd-profile-frames.ts +99 -0
  23. package/src/cmd-profile-spec.ts +24 -0
  24. package/src/cmd-profile.ts +164 -0
  25. package/src/cmd-repro-spec.ts +13 -1
  26. package/src/cmd-repro.ts +37 -5
  27. package/src/cmd-status-sample.ts +57 -0
  28. package/src/cmd-status-spec.ts +30 -0
  29. package/src/cmd-status.ts +108 -0
  30. package/src/cmd-token-spec.ts +5 -2
  31. package/src/cmd-token.ts +7 -3
  32. package/src/cmd-upgrade-codemods.ts +71 -0
  33. package/src/cmd-upgrade-spec.ts +19 -5
  34. package/src/cmd-upgrade.ts +91 -34
  35. package/src/codemods/agents-dev-mcp.ts +50 -0
  36. package/src/codemods/authenticator-session-refusal.ts +214 -0
  37. package/src/codemods/biome-no-default-export.ts +58 -0
  38. package/src/codemods/bunfig-island-coverage.ts +33 -0
  39. package/src/codemods/chart-dashboard.ts +73 -0
  40. package/src/codemods/ci-e2e-browser-stock.ts +75 -0
  41. package/src/codemods/ci-e2e-browser.ts +63 -0
  42. package/src/codemods/codemod.ts +58 -0
  43. package/src/codemods/define-error-leaf.ts +73 -0
  44. package/src/codemods/docs-ci-parts.ts +65 -0
  45. package/src/codemods/docs-gate-prose.ts +53 -0
  46. package/src/codemods/docs-island-rows.ts +31 -0
  47. package/src/codemods/docs-shipped-guards.ts +100 -0
  48. package/src/codemods/docs-test-services.ts +62 -0
  49. package/src/codemods/engine-diff.ts +104 -0
  50. package/src/codemods/engine-edits.ts +111 -0
  51. package/src/codemods/engine-fs.ts +95 -0
  52. package/src/codemods/engine.ts +191 -0
  53. package/src/codemods/format-edited-hook-3122.ts +28 -0
  54. package/src/codemods/format-edited-hook.ts +152 -0
  55. package/src/codemods/helm-alerts-objective.ts +105 -0
  56. package/src/codemods/helm-alerts-stock.ts +108 -0
  57. package/src/codemods/index.ts +56 -0
  58. package/src/codemods/metrics-probe-healthz.ts +47 -0
  59. package/src/codemods/pending.ts +36 -0
  60. package/src/codemods/repro-gitignore.ts +40 -0
  61. package/src/codemods/runtime-pin-lines.ts +109 -0
  62. package/src/codemods/runtime-pin.ts +116 -0
  63. package/src/codemods/solid-floor.ts +63 -0
  64. package/src/codemods/test-ports.ts +86 -0
  65. package/src/codemods/test-suites.ts +37 -0
  66. package/src/codemods/theme-toggle-mount-over.ts +70 -0
  67. package/src/codemods/vendored-guards.ts +186 -0
  68. package/src/codemods/verify-floor-skips.ts +88 -0
  69. package/src/codemods/verify-floor-steps.ts +90 -0
  70. package/src/coverage-island.ts +121 -0
  71. package/src/coverage-lcov.ts +49 -5
  72. package/src/coverage-remap.ts +146 -0
  73. package/src/db-replay-engine-prepared.ts +66 -0
  74. package/src/db-replay-engine-template.ts +156 -0
  75. package/src/db-replay-engine.ts +4 -0
  76. package/src/db-replay-scratch-reap.ts +54 -0
  77. package/src/deploy-verify-flags.ts +9 -2
  78. package/src/deploy-verify-grade.ts +10 -3
  79. package/src/dev-boot.ts +14 -1
  80. package/src/dev-dashboard-guard.ts +57 -10
  81. package/src/dev-host.ts +46 -0
  82. package/src/dev-tls-cache.ts +103 -0
  83. package/src/dev-tls-der.ts +69 -0
  84. package/src/dev-tls.ts +120 -0
  85. package/src/doctor-advisory-floors.ts +113 -0
  86. package/src/doctor-browser.ts +60 -0
  87. package/src/doctor-guards.ts +39 -86
  88. package/src/doctor-superseded.ts +67 -0
  89. package/src/error-codes-doctor.ts +12 -4
  90. package/src/error-codes-verify.ts +47 -0
  91. package/src/error-codes.ts +20 -23
  92. package/src/exercise-database.ts +47 -9
  93. package/src/exercise-push-device.ts +51 -0
  94. package/src/exercise-route-api.ts +74 -0
  95. package/src/exercise-routes.ts +14 -5
  96. package/src/exercise-services.ts +3 -1
  97. package/src/exercise-shard-flag.ts +47 -0
  98. package/src/fix-command.ts +2 -2
  99. package/src/generate-factories.ts +5 -11
  100. package/src/generate-feature-required.ts +9 -4
  101. package/src/generate-files.ts +26 -7
  102. package/src/generate-kinds.ts +5 -1
  103. package/src/guards-built-in-codes.ts +36 -0
  104. package/src/guards-built-in-refusal.ts +25 -0
  105. package/src/guards-built-in.ts +134 -0
  106. package/src/guards-materialize.ts +42 -0
  107. package/src/guards-paths.ts +37 -0
  108. package/src/guards-shipped-names.ts +38 -0
  109. package/src/guards-vendored.ts +73 -0
  110. package/src/guards.ts +105 -34
  111. package/src/index.ts +10 -0
  112. package/src/island-bundle-options.ts +48 -0
  113. package/src/island-bundle.ts +18 -46
  114. package/src/island-link.ts +5 -0
  115. package/src/island-outputs.ts +5 -0
  116. package/src/lint-findings.ts +3 -3
  117. package/src/mcp-errors-verify.ts +35 -0
  118. package/src/mcp-errors.ts +21 -20
  119. package/src/mcp-host-logs.ts +121 -0
  120. package/src/mcp-host.ts +12 -73
  121. package/src/measure-scope.ts +23 -3
  122. package/src/messages-floor.ts +19 -0
  123. package/src/messages-repro.ts +16 -2
  124. package/src/messages-status.ts +10 -0
  125. package/src/messages-upgrade.ts +15 -0
  126. package/src/messages.ts +22 -1
  127. package/src/registry.ts +4 -0
  128. package/src/repro-archive-collect.ts +161 -0
  129. package/src/repro-archive-write.ts +96 -0
  130. package/src/repro-archive.ts +161 -0
  131. package/src/repro-bundle.ts +8 -16
  132. package/src/repro-errors.ts +14 -2
  133. package/src/repro-framework.ts +53 -0
  134. package/src/repro-parse.ts +87 -0
  135. package/src/repro-redact.ts +218 -0
  136. package/src/repro-scrub.ts +257 -0
  137. package/src/role-start-types.ts +7 -0
  138. package/src/role-start.ts +4 -0
  139. package/src/serve-boot.ts +7 -1
  140. package/src/serve-env-tls.ts +57 -0
  141. package/src/solid-loader.ts +27 -10
  142. package/src/superseded-match.ts +87 -0
  143. package/src/superseded.ts +84 -0
  144. package/src/templates/bun-image.ts +48 -0
  145. package/src/templates/generate-export-rows.ts +136 -0
  146. package/src/templates/generate-import-rows.ts +186 -0
  147. package/src/templates/generate-rows-slice.ts +95 -0
  148. package/src/templates/github/ci.yml.ts +5 -1
  149. package/src/templates/guard-released-forms.ts +112 -0
  150. package/src/templates/guard-runtime-pin-test.ts +54 -0
  151. package/src/templates/guard-runtime-pin.ts +189 -0
  152. package/src/templates/scaffold-claude-agents.ts +6 -6
  153. package/src/templates/scaffold-claude-commands.ts +1 -1
  154. package/src/templates/scaffold-claude-hook.ts +18 -8
  155. package/src/templates/scaffold-claude.ts +2 -2
  156. package/src/templates/scaffold-db-package.ts +3 -0
  157. package/src/templates/scaffold-docs.ts +34 -30
  158. package/src/templates/scaffold-guards.ts +73 -39
  159. package/src/templates/scaffold-repo.ts +4 -8
  160. package/src/templates/scaffold-site.ts +4 -1
  161. package/src/templates/scaffold-suites.ts +72 -0
  162. package/src/templates/scaffold-test-services.ts +35 -10
  163. package/src/templates/scaffold-verify-floor.ts +53 -31
  164. package/src/templates/shapes/api.ts +4 -0
  165. package/src/templates/slice-foundation.ts +3 -3
  166. package/src/unthrown-codes.ts +3 -1
  167. package/src/upgrade-bun-floor.ts +4 -0
  168. package/src/upgrade-clean-tree.ts +54 -0
  169. package/src/upgrade-gate-codemods-install.ts +40 -0
  170. package/src/upgrade-gate-codemods.ts +151 -0
  171. package/src/upgrade-gate.ts +44 -7
  172. package/src/upgrade-guards-baseline.ts +43 -0
  173. package/src/upgrade-guards.ts +37 -2
  174. package/src/upgrade-lock.ts +118 -0
  175. package/src/upgrade-plan.ts +2 -1
  176. package/src/upgrade-report-codemods.ts +54 -0
  177. package/src/upgrade-report.ts +55 -27
  178. package/src/upgrade-signals.ts +91 -0
  179. package/src/upgrade-unfinished.ts +61 -0
  180. package/src/verify-coverage-run.ts +42 -11
  181. package/src/verify-e2e.ts +115 -4
  182. package/src/verify-floor.ts +27 -0
  183. package/src/verify-guard-baseline.ts +109 -0
  184. package/src/verify-live.ts +72 -0
  185. package/src/verify-merge-skips.ts +51 -0
  186. package/src/verify-merge.ts +36 -2
  187. package/src/verify-run.ts +48 -7
  188. package/src/verify-services.ts +287 -0
  189. package/src/verify-skip-reason.ts +53 -0
  190. package/src/verify-strict.ts +108 -0
  191. package/src/verify-test-command.ts +129 -0
  192. package/src/verify-tests.ts +39 -126
  193. package/types/babel-modules.d.ts +2 -0
  194. package/wiki/CLI-Reference.md +200 -27
  195. package/wiki/Caching-And-Invalidation.md +1 -1
  196. package/wiki/Entities-And-Migrations.md +1 -1
  197. package/wiki/Interface-Rules.md +17 -8
  198. package/wiki/Jobs-And-Workflows.md +3 -3
  199. package/wiki/Known-Gaps.md +5 -1
  200. package/wiki/MCP-And-AI.md +1 -1
  201. package/wiki/Observability.md +1 -0
  202. package/wiki/PWA-And-Offline.md +1 -1
  203. package/wiki/Project-Layout.md +4 -4
  204. package/wiki/Troubleshooting.md +3 -3
  205. package/wiki/Tutorial-05-Deploy-Free.md +2 -2
  206. package/wiki/Upgrading.md +8 -0
@@ -0,0 +1,100 @@
1
+ // 31.28.0: shipped guards run from the installed framework, never a `guards/` copy, so the app's
2
+ // CLAUDE.md names each by its guard name (`raw-fetch`, not `guards/raw-fetch.ts`), lists the
3
+ // runtime-pin rule, and says how a guard is set; the agents say the same. Prose: each edit lands
4
+ // where the text stands as `x new` wrote it, and is skipped silently where the app reworded it.
5
+
6
+ import { SHIPPED_GUARD_NAMES } from '../templates/scaffold-guards';
7
+ import type { Codemod, CodemodApp, CodemodResult } from './codemod';
8
+ import type { SnippetEdit } from './engine-edits';
9
+ import { editSnippets, mergeResults } from './engine-edits';
10
+
11
+ const CLAUDE = 'CLAUDE.md';
12
+ const lines = (...text: readonly string[]): string => text.join('\n');
13
+
14
+ const VENDORS =
15
+ "| Vendors | a server `fetch(` carries a `signal` in its own options — better, it is `outbound()` from `@ultimat3/core/outbound`: a deadline, the caller's signal, safe-only retry | `raw-fetch` |";
16
+ const RUNTIME =
17
+ "| Runtime | every Bun pin — `packageManager`, `.bun-version`, CI's `bun-version:`, the image's `FROM oven/bun:` — names the version `engines.bun` declares, and an image builds on a digest | `runtime-pin` |";
18
+
19
+ export const SHIPPED_GUARDS_EDITS: Readonly<Record<string, readonly SnippetEdit[]>> = {
20
+ [CLAUDE]: [
21
+ { from: VENDORS, to: lines(VENDORS, RUNTIME), optional: true },
22
+ {
23
+ from: lines(
24
+ '`guards/` is yours: each file is one rule, discovered by `bunx x verify` and run inside its',
25
+ '`boundaries` step. Delete one to drop the rule, and `bunx x g guard <name>` writes the next.',
26
+ ),
27
+ to: lines(
28
+ "Each lowercase name is a guard the framework ships, run on `bunx x verify`'s `boundaries` step",
29
+ 'from the installed version. `guards/shipped.json` sets one\'s severity (`"warning"`, `"off"`);',
30
+ "`bunx x g guard <name>` writes this app's own into `guards/`.",
31
+ ),
32
+ optional: true,
33
+ },
34
+ ],
35
+ '.claude/agents/server.md': [
36
+ {
37
+ from: lines(
38
+ '| Errors are instructions | never `throw new Error` — declare each code once with `defineError({ code, title, status, cause, fix })` from `@ultimat3/core/page`: a stable `X_SCREAMING_SNAKE` code, a cause and a `fix:` a caller can actually run. `guards/error-declared.ts` refuses a handwritten `UltimateError` subclass |',
39
+ ),
40
+ to: lines(
41
+ '| Errors are instructions | never `throw new Error` — declare each code once with `defineError({ code, title, status, cause, fix })` from `@ultimat3/core/page`: a stable `X_SCREAMING_SNAKE` code, a cause and a `fix:` a caller can actually run. the `error-declared` guard refuses a handwritten `UltimateError` subclass |',
42
+ ),
43
+ optional: true,
44
+ },
45
+ ],
46
+ '.claude/agents/web.md': [
47
+ {
48
+ from: lines(
49
+ "Every one of the last five is a build error, not a preference — `guards/` holds them and `bunx x verify`'s",
50
+ '`boundaries` step runs them. Read the guard rather than guessing at the rule.',
51
+ ),
52
+ to: lines(
53
+ 'Every one of the last five is a build error, not a preference — a guard the framework ships, run by',
54
+ "`bunx x verify`'s `boundaries` step. Read the guard's finding rather than guessing at the rule.",
55
+ ),
56
+ optional: true,
57
+ },
58
+ ],
59
+ };
60
+
61
+ const SHIPPED = new Set(SHIPPED_GUARD_NAMES);
62
+
63
+ /** A table row's `guards/<name>.ts` cell, for a guard the framework ships, as its bare name. */
64
+ const renamed = (source: string): string =>
65
+ source
66
+ .split('\n')
67
+ .map((line) =>
68
+ line.startsWith('| ')
69
+ ? line.replace(/`guards\/([a-z0-9-]+)\.ts`/g, (cell, name: string) =>
70
+ SHIPPED.has(name) ? `\`${name}\`` : cell,
71
+ )
72
+ : line,
73
+ )
74
+ .join('\n');
75
+
76
+ async function table(app: CodemodApp): Promise<CodemodResult> {
77
+ const source = await app.read(CLAUDE);
78
+ if (source === undefined) return { changed: [], skipped: [] };
79
+ const next = renamed(source);
80
+ if (next === source) return { changed: [], skipped: [] };
81
+ await app.write(CLAUDE, next);
82
+ return { changed: [CLAUDE], skipped: [] };
83
+ }
84
+
85
+ export const codemod: Codemod = {
86
+ id: 'docs-shipped-guards',
87
+ since: '31.28.0',
88
+ summary:
89
+ 'CLAUDE.md and .claude/agents name each shipped guard as the framework runs it, not as a guards/ copy',
90
+ async run(app) {
91
+ const results = [await table(app)];
92
+ // A runtime row only where none is: the insert matches the Vendors row, which stays.
93
+ const runtime = ((await app.read(CLAUDE)) ?? '').includes('| Runtime |');
94
+ for (const [path, edits] of Object.entries(SHIPPED_GUARDS_EDITS)) {
95
+ const todo = path === CLAUDE && runtime ? edits.slice(1) : edits;
96
+ results.push(await editSnippets(app, path, todo));
97
+ }
98
+ return mergeResults(results);
99
+ },
100
+ };
@@ -0,0 +1,62 @@
1
+ // 31.27.0: the app's CLAUDE.md and README.md say what the live and e2e suites run on, and that
2
+ // `bun run verify` starts the test services itself. Prose the app may have reworded: each edit
3
+ // lands where the text stands as `x new` wrote it, and is skipped silently where it does not.
4
+
5
+ import type { Codemod } from './codemod';
6
+ import type { SnippetEdit } from './engine-edits';
7
+ import { editSnippets, mergeResults } from './engine-edits';
8
+
9
+ const lines = (...text: readonly string[]): string => text.join('\n');
10
+
11
+ export const DOCS_TEST_SERVICES_EDITS: Readonly<Record<string, readonly SnippetEdit[]>> = {
12
+ 'CLAUDE.md': [
13
+ {
14
+ from: lines(
15
+ 'Every test the scaffold and the generators write is the idiom to copy. All of them run on the',
16
+ '`unit` step — in process, on the in-memory driver, with no database, browser or server.',
17
+ '',
18
+ 'A suite that needs a real server reads it from `docker/test-services.env`: Postgres 18, Redis, NATS',
19
+ 'and S3 from `docker/docker-compose.test.yml`, in RAM, with durability and logging off — CI starts',
20
+ 'it before `bun run verify`, a laptop with `docker compose -f docker/docker-compose.test.yml up -d',
21
+ '--wait` then `set -a; . docker/test-services.env; set +a`. A resource a test opens is held with',
22
+ ),
23
+ to: lines(
24
+ 'Every test the scaffold and the generators write is the idiom to copy. A `*.live.test.ts` runs',
25
+ 'on a real Postgres, a `*.e2e.test.ts` in a real browser; the rest on `unit`, in memory.',
26
+ '',
27
+ 'A suite that needs a real server reads it from `docker/test-services.env`: Postgres 18, Redis, NATS',
28
+ 'and S3 from `docker/docker-compose.test.yml`, in RAM, with durability and logging off.',
29
+ '`bun run verify` starts it itself when nothing answers at `TEST_DATABASE_URL` and Docker is',
30
+ 'there; by hand it is `docker compose -f docker/docker-compose.test.yml up -d --wait` then',
31
+ '`set -a; . docker/test-services.env; set +a`. A resource a test opens is held with',
32
+ ),
33
+ optional: true,
34
+ },
35
+ ],
36
+ 'README.md': [
37
+ {
38
+ from: lines(
39
+ 'Tests against real servers — Postgres 18, Redis, NATS, S3, in RAM and silent, as CI runs them:',
40
+ ),
41
+ to: lines(
42
+ 'Tests against real servers — Postgres 18, Redis, NATS, S3, in RAM and silent, as CI runs them.',
43
+ '`bun run verify` starts them when nothing answers and Docker is there; by hand:',
44
+ ),
45
+ optional: true,
46
+ },
47
+ ],
48
+ };
49
+
50
+ export const codemod: Codemod = {
51
+ id: 'docs-test-services',
52
+ since: '31.27.0',
53
+ summary:
54
+ 'CLAUDE.md and README.md: the live and e2e suites, and the test services verify starts itself',
55
+ async run(app) {
56
+ const results = [];
57
+ for (const [path, edits] of Object.entries(DOCS_TEST_SERVICES_EDITS)) {
58
+ results.push(await editSnippets(app, path, edits));
59
+ }
60
+ return mergeResults(results);
61
+ },
62
+ };
@@ -0,0 +1,104 @@
1
+ // The unified diff a codemod reports a file it would not overwrite with: what the template change
2
+ // wanted, for the author to apply by hand. LCS over the lines between the common ends, bounded:
3
+ // past `MAX_CELLS` the middle is a plain replace, still a correct diff, just not a minimal one.
4
+
5
+ const CONTEXT = 3;
6
+ const MAX_CELLS = 4_000_000;
7
+
8
+ type Op = { readonly kind: ' ' | '-' | '+'; readonly text: string };
9
+
10
+ const linesOf = (text: string): readonly string[] => {
11
+ if (text === '') return [];
12
+ const lines = text.split('\n');
13
+ return lines.at(-1) === '' ? lines.slice(0, -1) : lines;
14
+ };
15
+
16
+ function middleOps(a: readonly string[], b: readonly string[]): Op[] {
17
+ if (a.length * b.length > MAX_CELLS) {
18
+ return [
19
+ ...a.map((text): Op => ({ kind: '-', text })),
20
+ ...b.map((text): Op => ({ kind: '+', text })),
21
+ ];
22
+ }
23
+ const width = b.length + 1;
24
+ const table = new Uint32Array((a.length + 1) * width);
25
+ for (let i = a.length - 1; i >= 0; i -= 1) {
26
+ for (let j = b.length - 1; j >= 0; j -= 1) {
27
+ table[i * width + j] =
28
+ a[i] === b[j]
29
+ ? (table[(i + 1) * width + j + 1] ?? 0) + 1
30
+ : Math.max(table[(i + 1) * width + j] ?? 0, table[i * width + j + 1] ?? 0);
31
+ }
32
+ }
33
+ const ops: Op[] = [];
34
+ let i = 0;
35
+ let j = 0;
36
+ while (i < a.length || j < b.length) {
37
+ if (i < a.length && j < b.length && a[i] === b[j]) {
38
+ ops.push({ kind: ' ', text: a[i] ?? '' });
39
+ i += 1;
40
+ j += 1;
41
+ } else if (
42
+ i < a.length &&
43
+ (j === b.length || (table[(i + 1) * width + j] ?? 0) >= (table[i * width + j + 1] ?? 0))
44
+ ) {
45
+ // Removal first on a tie: a replaced line reads `-old` then `+new`, as git prints it.
46
+ ops.push({ kind: '-', text: a[i] ?? '' });
47
+ i += 1;
48
+ } else {
49
+ ops.push({ kind: '+', text: b[j] ?? '' });
50
+ j += 1;
51
+ }
52
+ }
53
+ return ops;
54
+ }
55
+
56
+ function editScript(a: readonly string[], b: readonly string[]): readonly Op[] {
57
+ let head = 0;
58
+ while (head < a.length && head < b.length && a[head] === b[head]) head += 1;
59
+ let tail = 0;
60
+ while (
61
+ tail < a.length - head &&
62
+ tail < b.length - head &&
63
+ a[a.length - 1 - tail] === b[b.length - 1 - tail]
64
+ ) {
65
+ tail += 1;
66
+ }
67
+ const same = (text: string): Op => ({ kind: ' ', text });
68
+ return [
69
+ ...a.slice(0, head).map(same),
70
+ ...middleOps(a.slice(head, a.length - tail), b.slice(head, b.length - tail)),
71
+ ...a.slice(a.length - tail).map(same),
72
+ ];
73
+ }
74
+
75
+ /** `path`'s change from `before` (undefined: the file is new) to `after`; '' when they are equal. */
76
+ export function unifiedDiff(path: string, before: string | undefined, after: string): string {
77
+ if (before === after) return '';
78
+ const ops = editScript(linesOf(before ?? ''), linesOf(after));
79
+ const out = [before === undefined ? '--- /dev/null' : `--- a/${path}`, `+++ b/${path}`];
80
+ let index = 0;
81
+ while (index < ops.length) {
82
+ const first = ops.findIndex((op, at) => at >= index && op.kind !== ' ');
83
+ if (first === -1) break;
84
+ // A hunk runs while the gap between two changes is at most twice the context.
85
+ let last = first;
86
+ for (let at = first + 1; at < ops.length && at - last <= 2 * CONTEXT; at += 1) {
87
+ if (ops[at]?.kind !== ' ') last = at;
88
+ }
89
+ const start = Math.max(index, first - CONTEXT);
90
+ const end = Math.min(ops.length, last + CONTEXT + 1);
91
+ const prior = ops.slice(0, start);
92
+ const oldStart = prior.filter((op) => op.kind !== '+').length;
93
+ const newStart = prior.filter((op) => op.kind !== '-').length;
94
+ const hunk = ops.slice(start, end);
95
+ const oldCount = hunk.filter((op) => op.kind !== '+').length;
96
+ const newCount = hunk.filter((op) => op.kind !== '-').length;
97
+ const at = (from: number, count: number): string =>
98
+ `${String(count === 0 ? from : from + 1)},${String(count)}`;
99
+ out.push(`@@ -${at(oldStart, oldCount)} +${at(newStart, newCount)} @@`);
100
+ for (const op of hunk) out.push(`${op.kind}${op.text}`);
101
+ index = end;
102
+ }
103
+ return `${out.join('\n')}\n`;
104
+ }
@@ -0,0 +1,111 @@
1
+ // The two edits a template codemod is made of: swap exact snippets of the old template for the new
2
+ // ones, or add a file the template added. Mechanical or nothing: a snippet the app rewrote leaves
3
+ // the file as it is, reported with the template's own change as a diff to apply by hand.
4
+
5
+ import type { CodemodApp, CodemodResult } from './codemod';
6
+ import { unifiedDiff } from './engine-diff';
7
+
8
+ export interface SnippetEdit {
9
+ /** The old template's exact text. */
10
+ readonly from: string;
11
+ /** What the new template says in its place. */
12
+ readonly to: string;
13
+ /** Prose (a comment) the app may have reworded: swapped when found, never a reason to skip. */
14
+ readonly optional?: boolean;
15
+ }
16
+
17
+ const NOTHING: CodemodResult = { changed: [], skipped: [] };
18
+
19
+ /** A file's text as LF without a BOM, and how to put both back: a Windows checkout is supported. */
20
+ export interface FileText {
21
+ readonly text: string;
22
+ readonly restore: (text: string) => string;
23
+ }
24
+
25
+ export function fileText(source: string): FileText {
26
+ const bom = source.startsWith('\uFEFF') ? '\uFEFF' : '';
27
+ const body = source.slice(bom.length);
28
+ const crlf = body.includes('\r\n');
29
+ return {
30
+ text: crlf ? body.replaceAll('\r\n', '\n') : body,
31
+ restore: (text) => `${bom}${crlf ? text.replaceAll('\n', '\r\n') : text}`,
32
+ };
33
+ }
34
+
35
+ /** `path` read as LF text; undefined when the app has no such file. */
36
+ export async function readText(app: CodemodApp, path: string): Promise<FileText | undefined> {
37
+ const source = await app.read(path);
38
+ return source === undefined ? undefined : fileText(source);
39
+ }
40
+
41
+ /**
42
+ * Carried across. A removal (`to` inside `from`): `from` is gone. An insert (`from` inside `to`):
43
+ * `to` is there. A swap: `to` is there and `from` is not.
44
+ */
45
+ const done = (source: string, edit: SnippetEdit): boolean => {
46
+ if (edit.from.includes(edit.to)) return !source.includes(edit.from);
47
+ if (edit.to.includes(edit.from)) return source.includes(edit.to);
48
+ return source.includes(edit.to) && !source.includes(edit.from);
49
+ };
50
+
51
+ const count = (source: string, part: string): number => source.split(part).length - 1;
52
+
53
+ /**
54
+ * Every pending `from` swapped for its `to`, or nothing: an edit already carried across is done;
55
+ * one whose `from` is gone too means the app wrote its own, and one whose `from` stands in more than
56
+ * one place is a guess — which the template meant is not in the text — so the file is the author's.
57
+ * Matched on LF text without a BOM, written back with the file's own line ending and BOM.
58
+ */
59
+ export async function editSnippets(
60
+ app: CodemodApp,
61
+ path: string,
62
+ edits: readonly SnippetEdit[],
63
+ ): Promise<CodemodResult> {
64
+ const file = await readText(app, path);
65
+ if (file === undefined) return NOTHING;
66
+ const source = file.text;
67
+ const pending = edits.filter((edit) => !done(source, edit));
68
+ if (pending.every((edit) => edit.optional === true && !source.includes(edit.from))) {
69
+ return NOTHING;
70
+ }
71
+ const wanted = (side: 'from' | 'to'): string =>
72
+ `${edits.map((edit) => edit[side]).join('\n\n')}\n`;
73
+ const skip = (reason: string): CodemodResult => ({
74
+ changed: [],
75
+ skipped: [{ path, reason, diff: unifiedDiff(path, wanted('from'), wanted('to')) }],
76
+ });
77
+ const missing = pending.filter((edit) => edit.optional !== true && !source.includes(edit.from));
78
+ if (missing.length > 0) {
79
+ return skip(
80
+ `the app's copy no longer holds the template text this change replaces (${missing.map((edit) => JSON.stringify(edit.from.split('\n')[0] ?? '')).join(', ')}), so the diff below is the template's change, to make by hand`,
81
+ );
82
+ }
83
+ const twice = pending.find((edit) => count(source, edit.from) > 1);
84
+ if (twice !== undefined) {
85
+ return skip(
86
+ `the template text this change replaces stands in ${String(count(source, twice.from))} places (${JSON.stringify(twice.from.split('\n')[0] ?? '')}), and which one it meant is not decidable: the diff below is the change, to make by hand`,
87
+ );
88
+ }
89
+ let next = source;
90
+ for (const edit of pending) next = next.replace(edit.from, () => edit.to);
91
+ if (next === source) return NOTHING;
92
+ await app.write(path, file.restore(next));
93
+ return { changed: [path], skipped: [] };
94
+ }
95
+
96
+ /** A file the template added since: written when the app has none, never over one it has. */
97
+ export async function writeIfAbsent(
98
+ app: CodemodApp,
99
+ path: string,
100
+ source: string,
101
+ ): Promise<CodemodResult> {
102
+ if (await app.exists(path)) return NOTHING;
103
+ await app.write(path, source);
104
+ return { changed: [path], skipped: [] };
105
+ }
106
+
107
+ /** Several results as one, in order. */
108
+ export const mergeResults = (results: readonly CodemodResult[]): CodemodResult => ({
109
+ changed: results.flatMap((result) => result.changed),
110
+ skipped: results.flatMap((result) => result.skipped),
111
+ });
@@ -0,0 +1,95 @@
1
+ // The `CodemodApp` over a real app root: posix paths relative to it in and out, refused when they
2
+ // resolve outside it — lexically or through a symlink. A glob skips `node_modules/` and `.git/`,
3
+ // which no scaffold-owned file is in.
4
+
5
+ // why: Bun has no file-removal, rename, lstat or realpath primitive; `rm` with `force` makes a
6
+ // removal of nothing no error, `rename` lands a write whole, and only `realpath` answers where a
7
+ // symlinked component really points.
8
+ import { lstat, realpath, rename, rm } from 'node:fs/promises';
9
+ // why: Bun exposes no path-resolve primitive; containment is decided on the resolved path.
10
+ import { dirname, resolve, sep } from 'node:path';
11
+ import { ScaffoldPathEscapeError } from '../errors';
12
+ import type { CodemodApp } from './codemod';
13
+
14
+ const SKIPPED = /^(?:node_modules|\.git)\//;
15
+
16
+ const FIX =
17
+ 'x upgrade codemods --from 0.0.0 --dry-run --json # names the codemod that asked for the path; report it with that output';
18
+
19
+ const inside = (base: string, target: string): boolean => target.startsWith(`${base}${sep}`);
20
+
21
+ /** Nothing at this path (or a file where a directory was named): keep walking up. */
22
+ const absent = (error: unknown): boolean => {
23
+ const code = typeof error === 'object' && error !== null ? Reflect.get(error, 'code') : undefined;
24
+ return code === 'ENOENT' || code === 'ENOTDIR';
25
+ };
26
+
27
+ /**
28
+ * The absolute path, once it is inside the root twice over: lexically, and after following every
29
+ * symlink on the way — the deepest component that exists is resolved, and must land under the
30
+ * root's own real path. A dangling link resolves nowhere, so it is refused rather than followed.
31
+ */
32
+ async function contained(root: string, path: string): Promise<string> {
33
+ const base = resolve(root);
34
+ const target = resolve(base, path);
35
+ const refuse = (): never => {
36
+ throw new ScaffoldPathEscapeError({ path, dir: base, fix: FIX });
37
+ };
38
+ if (target === base || !inside(base, target)) refuse();
39
+ const realBase = await realpath(base);
40
+ for (let probe = target; probe !== base; probe = dirname(probe)) {
41
+ const exists = await lstat(probe).then(
42
+ () => true,
43
+ (error: unknown) => (absent(error) ? false : Promise.reject(error)),
44
+ );
45
+ if (!exists) continue;
46
+ const real = await realpath(probe).catch(refuse);
47
+ if (real !== realBase && !inside(realBase, real)) refuse();
48
+ break;
49
+ }
50
+ return target;
51
+ }
52
+
53
+ /**
54
+ * `source` at `target`, whole or not at all: written beside it under a unique name, then renamed
55
+ * over it — a crash leaves the old file or the new one, never half of one, and no stray temp.
56
+ */
57
+ export async function landFile(
58
+ target: string,
59
+ source: string,
60
+ move: (from: string, to: string) => Promise<void> = rename,
61
+ ): Promise<void> {
62
+ const temp = `${target}.x-codemod-${String(process.pid)}-${crypto.randomUUID()}.tmp`;
63
+ await Bun.write(temp, source);
64
+ try {
65
+ await move(temp, target);
66
+ } catch (error) {
67
+ await rm(temp, { force: true });
68
+ throw error;
69
+ }
70
+ }
71
+
72
+ export function fsCodemodApp(root: string): CodemodApp {
73
+ return {
74
+ root,
75
+ async read(path) {
76
+ const file = Bun.file(await contained(root, path));
77
+ return (await file.exists()) ? await file.text() : undefined;
78
+ },
79
+ async write(path, source) {
80
+ await landFile(await contained(root, path), source);
81
+ },
82
+ async remove(path) {
83
+ await rm(await contained(root, path), { force: true });
84
+ },
85
+ exists: async (path) => Bun.file(await contained(root, path)).exists(),
86
+ async glob(pattern) {
87
+ const paths: string[] = [];
88
+ for await (const path of new Bun.Glob(pattern).scan({ cwd: root, dot: true })) {
89
+ const posix = path.replaceAll('\\', '/');
90
+ if (!SKIPPED.test(posix)) paths.push(posix);
91
+ }
92
+ return paths.sort();
93
+ },
94
+ };
95
+ }
@@ -0,0 +1,191 @@
1
+ // The codemod engine: the codemods a hop owes (`since` in (from, to], version then id), each run
2
+ // over a staged view of the app so the next one sees its output, a throw costs only its own
3
+ // writes, and `--dry-run` is the same run minus the final flush. Pure over `CodemodApp`.
4
+
5
+ import { renderThrowable } from '@ultimat3/core';
6
+ import { compareVersions } from '../upgrade-plan';
7
+ import type { Codemod, CodemodApp, CodemodSkip } from './codemod';
8
+
9
+ export interface CodemodOutcome {
10
+ readonly id: string;
11
+ readonly since: string;
12
+ readonly summary: string;
13
+ /** The files this codemod left different from how it found them, written or removed. */
14
+ readonly changed: readonly string[];
15
+ readonly skipped: readonly CodemodSkip[];
16
+ }
17
+
18
+ export interface CodemodsReport {
19
+ readonly from: string;
20
+ readonly to: string;
21
+ readonly dryRun: boolean;
22
+ /** Every codemod that ran, in the order it ran, whether or not it changed anything. */
23
+ readonly applied: readonly CodemodOutcome[];
24
+ }
25
+
26
+ /**
27
+ * Release order on the `major.minor.patch` triple: a prerelease (`32.0.0-next.1`) is its release,
28
+ * which carries every codemod `since` it — `compareVersions` alone reads it as 0.0.0.
29
+ */
30
+ const compareRelease = (a: string, b: string): number =>
31
+ compareVersions(a.split('-')[0] ?? a, b.split('-')[0] ?? b);
32
+
33
+ /** The codemods a hop from `from` to `to` owes, in the order they run. */
34
+ export function pendingCodemods(
35
+ codemods: readonly Codemod[],
36
+ from: string,
37
+ to: string,
38
+ ): readonly Codemod[] {
39
+ return codemods
40
+ .filter(
41
+ (codemod) =>
42
+ compareRelease(codemod.since, from) > 0 && compareRelease(codemod.since, to) <= 0,
43
+ )
44
+ .sort((a, b) => compareRelease(a.since, b.since) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
45
+ }
46
+
47
+ /** A path's staged state: its new text, or null for removed. */
48
+ type Staged = Map<string, string | null>;
49
+
50
+ /** The bytes the run first saw at each path it touched (undefined: no file): what a flush checks. */
51
+ type Seen = Map<string, string | undefined>;
52
+
53
+ /** `base` as `layers` leave it: the newest layer that names a path answers for it. */
54
+ function stagedView(
55
+ base: CodemodApp,
56
+ layers: readonly Staged[],
57
+ top: Staged,
58
+ seen: Seen,
59
+ ): CodemodApp {
60
+ const baseRead = async (path: string): Promise<string | undefined> => {
61
+ if (seen.has(path)) return seen.get(path);
62
+ const text = await base.read(path);
63
+ seen.set(path, text);
64
+ return text;
65
+ };
66
+ const lookup = (path: string): string | null | undefined => {
67
+ for (const layer of [top, ...[...layers].reverse()]) {
68
+ if (layer.has(path)) return layer.get(path);
69
+ }
70
+ return undefined;
71
+ };
72
+ const read = async (path: string): Promise<string | undefined> => {
73
+ const staged = lookup(path);
74
+ if (staged === null) return undefined;
75
+ return staged ?? (await baseRead(path));
76
+ };
77
+ return {
78
+ root: base.root,
79
+ read,
80
+ exists: async (path) => (await read(path)) !== undefined,
81
+ write: async (path, source) => {
82
+ await baseRead(path);
83
+ top.set(path, source);
84
+ },
85
+ remove: async (path) => {
86
+ await baseRead(path);
87
+ top.set(path, null);
88
+ },
89
+ glob: async (pattern) => {
90
+ const glob = new Bun.Glob(pattern);
91
+ const paths = new Set(await base.glob(pattern));
92
+ for (const layer of [...layers, top]) {
93
+ for (const [path, text] of layer) {
94
+ if (!glob.match(path)) continue;
95
+ if (text === null) paths.delete(path);
96
+ else paths.add(path);
97
+ }
98
+ }
99
+ const held: string[] = [];
100
+ for (const path of paths) if ((await read(path)) !== undefined) held.push(path);
101
+ return held.sort();
102
+ },
103
+ };
104
+ }
105
+
106
+ /** The paths a layer really changed: a write of the bytes already there is none. */
107
+ async function changedBy(layer: Staged, before: CodemodApp): Promise<readonly string[]> {
108
+ const changed: string[] = [];
109
+ for (const [path, text] of layer) {
110
+ if ((text ?? undefined) !== (await before.read(path))) changed.push(path);
111
+ }
112
+ return changed.sort();
113
+ }
114
+
115
+ export async function runCodemods(input: {
116
+ readonly app: CodemodApp;
117
+ readonly codemods: readonly Codemod[];
118
+ readonly from: string;
119
+ readonly to: string;
120
+ readonly dryRun: boolean;
121
+ }): Promise<CodemodsReport> {
122
+ const { app, from, to, dryRun } = input;
123
+ const layers: Staged[] = [];
124
+ const seen: Seen = new Map();
125
+ const applied: CodemodOutcome[] = [];
126
+ for (const codemod of pendingCodemods(input.codemods, from, to)) {
127
+ const top: Staged = new Map();
128
+ const before = stagedView(app, layers, new Map(), seen);
129
+ const head = { id: codemod.id, since: codemod.since, summary: codemod.summary };
130
+ try {
131
+ const result = await codemod.run(stagedView(app, layers, top, seen));
132
+ const changed = await changedBy(top, before);
133
+ layers.push(top);
134
+ applied.push({ ...head, changed, skipped: result.skipped });
135
+ } catch (error) {
136
+ // A framework bug, never the app's: its half-done writes go, and the next codemod still runs.
137
+ const reason = `the codemod threw, so it changed nothing: ${renderThrowable(error)}`;
138
+ applied.push({ ...head, changed: [], skipped: [{ path: '.', reason }] });
139
+ }
140
+ }
141
+ if (dryRun) return { from, to, dryRun, applied };
142
+ const final = new Map<string, string | null>();
143
+ for (const layer of layers) for (const [path, text] of layer) final.set(path, text);
144
+ const moved = await movedSince(app, final, seen);
145
+ if (moved.length > 0) return { from, to, dryRun, applied: refused(applied, moved) };
146
+ await flush(app, final);
147
+ return { from, to, dryRun, applied };
148
+ }
149
+
150
+ /** The staged paths whose bytes on disk are no longer the ones the run read. */
151
+ async function movedSince(
152
+ app: CodemodApp,
153
+ final: ReadonlyMap<string, string | null>,
154
+ seen: Seen,
155
+ ): Promise<readonly string[]> {
156
+ const moved: string[] = [];
157
+ for (const path of final.keys()) {
158
+ if (seen.has(path) && (await app.read(path)) !== seen.get(path)) moved.push(path);
159
+ }
160
+ return moved;
161
+ }
162
+
163
+ /** Nothing lands: each moved file is said, on the codemod that would have written it. */
164
+ function refused(
165
+ applied: readonly CodemodOutcome[],
166
+ moved: readonly string[],
167
+ ): readonly CodemodOutcome[] {
168
+ const reason =
169
+ 'changed on disk while the codemods ran, so no file was written: rerun x upgrade codemods on the tree as it is now';
170
+ return applied.map((one) => ({
171
+ ...one,
172
+ changed: [],
173
+ skipped: [
174
+ ...one.skipped,
175
+ ...one.changed.filter((path) => moved.includes(path)).map((path) => ({ path, reason })),
176
+ ],
177
+ }));
178
+ }
179
+
180
+ /**
181
+ * Writes first, removals after: interrupted between them, the tree holds both the old evidence and
182
+ * the new file — never neither, which a rerun would read as a different app.
183
+ */
184
+ async function flush(app: CodemodApp, final: ReadonlyMap<string, string | null>): Promise<void> {
185
+ for (const [path, text] of final) {
186
+ if (text !== null && text !== (await app.read(path))) await app.write(path, text);
187
+ }
188
+ for (const [path, text] of final) {
189
+ if (text === null && (await app.read(path)) !== undefined) await app.remove(path);
190
+ }
191
+ }