@astryxdesign/cli 0.7.5-canary.bc40b80 → 0.7.5-canary.c26ae3f

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 (44) hide show
  1. package/README.md +1 -1
  2. package/api/integration/pack-check.lifecycle-output.test.mjs +24 -1
  3. package/api/integration/pack-check.mjs +10 -4
  4. package/api/integration/pack-check.test.mjs +5 -1
  5. package/api/upgrade/_adapter.d.mts +2 -0
  6. package/api/upgrade/run/failure-receipt.test.mjs +212 -0
  7. package/api/upgrade/run/run.mjs +251 -10
  8. package/api/upgrade/upgrade.doc.mjs +4 -4
  9. package/api/upgrade/upgrade.mjs +19 -4
  10. package/api/upgrade/upgrade.type.d.mts +12 -1
  11. package/api/upgrade/upgrade.type.mjs +17 -4
  12. package/assets/codemods/__tests__/runner.symlinks.test.mjs +205 -0
  13. package/assets/codemods/__tests__/runner.unparseable.test.mjs +457 -0
  14. package/assets/codemods/integration-runner.mjs +8 -2
  15. package/assets/codemods/integration-runner.protection.test.mjs +53 -0
  16. package/assets/codemods/parse.mjs +94 -0
  17. package/assets/codemods/run-codemod.mjs +109 -5
  18. package/assets/codemods/runner.mjs +108 -10
  19. package/assets/codemods/transform-prop.mjs +99 -49
  20. package/assets/codemods/transform-prop.test.mjs +36 -1
  21. package/assets/codemods/transforms/v0.1.3/__tests__/migrate-layout-components-to-experimental.test.mjs +216 -2
  22. package/assets/codemods/transforms/v0.1.3/migrate-layout-components-to-experimental.mjs +88 -6
  23. package/assets/codemods/transforms/v0.6.0/migrate-astryx-theme-selectors-to-data-attrs.mjs +4 -3
  24. package/assets/codemods/transforms/v0.7.0/__tests__/migrate-deprecated-theme-surface.test.mjs +207 -6
  25. package/assets/codemods/transforms/v0.7.0/__tests__/validate-data-token-ownership.test.mjs +123 -70
  26. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface-v0.6-data.mjs +6 -1
  27. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface.mjs +244 -42
  28. package/assets/codemods/transforms/v0.7.0/validate-data-token-ownership.mjs +19 -77
  29. package/assets/docs/tree/styling-advanced.doc.mjs +1 -1
  30. package/assets/templates/blocks/components/CodeBlock/CodeBlockBashCommand.doc.mjs +1 -1
  31. package/assets/templates/blocks/components/CodeBlock/CodeBlockBashCommand.tsx +10 -2
  32. package/assets/templates/pages/library/page.tsx +1 -2
  33. package/authoring/codemod/type.ts +10 -0
  34. package/clients/cli/commands/upgrade.doc.mjs +27 -0
  35. package/clients/cli/commands/upgrade.file-protection.test.mjs +175 -0
  36. package/clients/cli/commands/upgrade.flag-help.test.mjs +37 -0
  37. package/clients/cli/commands/upgrade.integration-policy.test.mjs +103 -0
  38. package/clients/cli/commands/upgrade.mjs +9 -2
  39. package/foundation/response/base.d.ts +7 -0
  40. package/foundation/response/error-codes.doc.mjs +3 -2
  41. package/foundation/response/error-codes.mjs +1 -1
  42. package/foundation/response/json.d.mts +10 -3
  43. package/foundation/response/json.mjs +16 -4
  44. package/package.json +10 -9
@@ -1,13 +1,17 @@
1
1
  // Copyright (c) Meta Platforms, Inc. and affiliates.
2
2
 
3
3
  /**
4
- * @file Report data-token consumers that need an ownership migration.
4
+ * @file Reject stale generated theme CSS that still owns data-token defaults.
5
5
  *
6
- * @input Consumer JavaScript/TypeScript source and generated theme CSS
7
- * @output No rewritten source; actionable upgrade errors for fallback-less
8
- * `var(--color-data-*)` uses (in JS strings, embedded or whole, and in CSS)
9
- * and stale generated root-default artifacts
10
- * @position Next-release upgrade validation for spec:AST-066
6
+ * @input Generated theme CSS
7
+ * @output No rewritten source; an upgrade error for a generated theme
8
+ * stylesheet that still declares data-color defaults at `:root`
9
+ * @position Next-release upgrade validation for spec:AST-066 FR19
10
+ *
11
+ * Raw `var(--color-data-*)` uses are not checked: prebuilt
12
+ * `@astryxdesign/core/astryx.css` and the `@astryxdesign/build` PostCSS
13
+ * integration define all 56 defaults, and other source builds read data
14
+ * colors through `dataVars` (spec:AST-066 FR3/FR4).
11
15
  */
12
16
 
13
17
  import * as path from 'node:path';
@@ -15,87 +19,25 @@ import * as path from 'node:path';
15
19
  export const meta = {
16
20
  title: 'Validate data-token ownership',
17
21
  description:
18
- 'Reports fallback-less data-token var() uses in source strings and stylesheets for manual CSS/non-CSS migration, and stale generated theme CSS that still owns root defaults.',
19
- fileExtensions: ['.tsx', '.ts', '.jsx', '.js', '.mjs', '.cjs', '.css'],
22
+ 'Reports generated theme CSS that still emits the canonical data-color defaults at :root, so it can be rebuilt with `astryx theme build`.',
23
+ fileExtensions: ['.css'],
20
24
  };
21
25
 
22
- // A use without a fallback; `var(--color-data-x, <fallback>)` stays valid.
23
- const DIRECT_DATA_VAR = /var\(\s*(--color-data-[a-z0-9-]+)\s*\)/u;
24
- const CSS_COMMENT = /\/\*[\s\S]*?\*\//gu;
25
26
  const GENERATED_THEME_HEADER = '@generated by `astryx theme build`';
26
27
  const ROOT_DATA_DECLARATION = /:root\s*\{[^}]*--color-data-/su;
27
28
 
28
- /** @param {any} node */
29
- function staticString(node) {
30
- if (
31
- (node?.type === 'StringLiteral' || node?.type === 'Literal') &&
32
- typeof node.value === 'string'
33
- ) {
34
- return node.value;
35
- }
36
- if (node?.type === 'TemplateLiteral') {
37
- // Each static chunk of the template; a use can sit between expressions.
38
- return (node.quasis ?? [])
39
- .map((/** @type {any} */ q) => q?.value?.cooked ?? q?.value?.raw ?? '')
40
- .join('\u0000');
41
- }
42
- return undefined;
43
- }
44
-
45
29
  /**
46
30
  * @param {import('../../../../authoring/codemod/type').AstryxCodemodFile} file
47
- * @param {import('../../../../authoring/codemod/type').CodemodTransformApi} api
48
31
  * @returns {undefined}
49
32
  */
50
- export default function validateDataTokenOwnership(file, api) {
51
- if (!file.source.includes('--color-data-')) return undefined;
52
-
53
- if (path.extname(file.path) === '.css') {
54
- if (
55
- file.source.includes(GENERATED_THEME_HEADER) &&
56
- ROOT_DATA_DECLARATION.test(file.source)
57
- ) {
58
- throw new Error(
59
- 'This generated theme CSS still emits canonical data defaults at :root. Rebuild it with `astryx theme build`; defaults come from source-compiled dataVars consumers or @astryxdesign/core/astryx.css in prebuilt mode.',
60
- );
61
- }
62
- const uncommented = file.source.replace(CSS_COMMENT, comment =>
63
- comment.replace(/[^\n]/gu, ' '),
64
- );
65
- const cssMatch = DIRECT_DATA_VAR.exec(uncommented);
66
- if (cssMatch) {
67
- const line = uncommented.slice(0, cssMatch.index).split('\n').length;
68
- throw new Error(
69
- `Raw var(${cssMatch[1]}) without a fallback at line ${line} needs an availability check: load @astryxdesign/core/astryx.css in prebuilt mode, ensure a source-compiled dataVars consumer retains the group, or add an explicit fallback. CSS-capable code imports dataVars from @astryxdesign/core/theme/dataTokens.stylex.`,
70
- );
71
- }
72
- return undefined;
73
- }
74
-
75
- const j = api.jscodeshift;
76
- const root = j(file.source);
77
- /** @type {{token: string, line: number|null}|null} */
78
- let found = null;
79
- const inspect = (/** @type {any} */ node) => {
80
- if (found) return;
81
- const value = staticString(node);
82
- const match =
83
- typeof value === 'string' ? value.match(DIRECT_DATA_VAR) : null;
84
- if (match) {
85
- found = {token: match[1], line: node.loc?.start?.line ?? null};
86
- }
87
- };
88
-
89
- /** @param {any} nodePath */
90
- const inspectPath = nodePath => inspect(nodePath.node);
91
- root.find(j.StringLiteral).forEach(inspectPath);
92
- root.find(j.Literal).forEach(inspectPath);
93
- root.find(j.TemplateLiteral).forEach(inspectPath);
94
-
95
- if (found) {
96
- const {token, line} = found;
33
+ export default function validateDataTokenOwnership(file) {
34
+ if (
35
+ path.extname(file.path) === '.css' &&
36
+ file.source.includes(GENERATED_THEME_HEADER) &&
37
+ ROOT_DATA_DECLARATION.test(file.source)
38
+ ) {
97
39
  throw new Error(
98
- `Direct var(${token})${line == null ? '' : ` at line ${line}`} needs manual migration: CSS-capable code imports dataVars from @astryxdesign/core/theme/dataTokens.stylex and, in prebuilt mode, loads @astryxdesign/core/astryx.css; Canvas and other non-CSS APIs use resolveThemeToken() or useTheme().token().`,
40
+ 'This generated theme CSS still emits canonical data defaults at :root. Rebuild it with `astryx theme build`; defaults come from @astryxdesign/core/astryx.css in prebuilt mode, and in a source build from the @astryxdesign/build PostCSS integration or dataVars imports.',
99
41
  );
100
42
  }
101
43
  return undefined;
@@ -142,7 +142,7 @@ const overrides = stylex.create({
142
142
  },
143
143
  {
144
144
  type: 'prose',
145
- text: 'The upgrade treats a `components` map as a theme when it belongs to a `defineTheme()` call imported from Astryx, an object typed as an Astryx theme, or a theme object with a static `name` whose component entries are style objects. It leaves computed theme keys, unqualified classes, unknown consumer classes, declarations, comments, and CSS inside JavaScript or TypeScript strings unchanged. It adds `TODO(astryx upgrade)` when a map has both an old and a canonical key, and when a bare class Astryx once emitted has no known meaning on the target it qualifies. Review each TODO by hand.',
145
+ text: 'The upgrade treats a `components` map as a theme when it belongs to a `defineTheme()` call imported from Astryx, an object typed as an Astryx theme, or the theme object a same-stem theme descriptor (`<stem>.doc.mjs`) declares: the top-level binding exported as `<stem>`, with a static `name` and component entries that are style objects. A look-alike object anywhere else, such as a theme object from another library in the same file, is not an Astryx theme. It leaves computed theme keys, unqualified classes, unknown consumer classes, declarations, comments, and CSS inside JavaScript or TypeScript strings unchanged. It adds `TODO(astryx upgrade)` when a map has both an old and a canonical key, and when a bare class Astryx once emitted has no known meaning on the target it qualifies. Review each TODO by hand.',
146
146
  },
147
147
  ],
148
148
  },
@@ -7,7 +7,7 @@ export const doc = {
7
7
  name: 'Code — Snippet',
8
8
  displayName: 'Code — Snippet',
9
9
  description:
10
- 'Short terminal commands with a copy button and no line numbers. Use for install instructions or one-liner commands that readers will paste directly.',
10
+ 'Short terminal commands with no header: the copy button sits in its own column beside the code, so a one-line command reads as a single row and a long line ends before the button instead of running under it. Use for install instructions or one-liner commands that readers will paste directly.',
11
11
  isReady: true,
12
12
  aspectRatio: 16 / 9,
13
13
  componentsUsed: ['CodeBlock', 'Stack'],
@@ -11,13 +11,21 @@ export default function CodeBlockBashCommand() {
11
11
  <CodeBlock
12
12
  code="npm install @astryxdesign/core"
13
13
  language="bash"
14
- hasCopyButton
14
+ hasLanguageLabel={false}
15
15
  style={{width: '100%'}}
16
16
  />
17
17
  <CodeBlock
18
18
  code="yarn add @astryxdesign/theme-neutral"
19
19
  language="bash"
20
- hasCopyButton
20
+ hasLanguageLabel={false}
21
+ style={{width: '100%'}}
22
+ />
23
+ <CodeBlock
24
+ code={
25
+ 'astryx upgrade --from 0.6.0 --apply --path apps/web/src --install-deps\nnpm run build'
26
+ }
27
+ language="bash"
28
+ hasLanguageLabel={false}
21
29
  style={{width: '100%'}}
22
30
  />
23
31
  </VStack>
@@ -193,8 +193,7 @@ const ITEMS: LibraryItem[] = [
193
193
  {
194
194
  id: '18',
195
195
  name: 'MobileNav',
196
- description:
197
- 'Bottom tab bar for mobile viewports with icon and label slots.',
196
+ description: 'Slide-out navigation drawer for mobile viewports.',
198
197
  category: 'Navigation',
199
198
  type: 'Pattern',
200
199
  imageUrl:
@@ -141,6 +141,16 @@ export interface CodemodRunResult {
141
141
  generated: boolean;
142
142
  command?: string;
143
143
  }>;
144
+ /**
145
+ * Protected files left for manual review because their own source does not
146
+ * parse, so no change can be proven in them. They do not fail the run.
147
+ */
148
+ declinedCandidates?: Array<{
149
+ file: string;
150
+ codemod: string;
151
+ location?: string;
152
+ reason: string;
153
+ }>;
144
154
  errors: Array<{file: string; codemod: string; error: string}>;
145
155
  }
146
156
 
@@ -157,6 +157,13 @@ export const doc = {
157
157
  'it is an installed dependency (such as anything in `node_modules`), is inside `.git`, `.hg`, or `.sl`, is a symbolic link, or is outside the project',
158
158
  ],
159
159
  },
160
+ {
161
+ type: 'prose',
162
+ text:
163
+ 'upgrade does not scan installed dependencies or version-control folders at all, including through a symbolic link: ' +
164
+ 'a symlinked `node_modules`, or a link whose target is inside one or inside a package store such as `.yarn/cache`, is skipped. ' +
165
+ 'Other symbolically linked folders are scanned so a change they need is reported, but nothing is written through them.',
166
+ },
160
167
  {
161
168
  type: 'prose',
162
169
  text:
@@ -194,5 +201,25 @@ export const doc = {
194
201
  '`Command:` line in its header, such as `// Command: pnpm run gen:panel`; upgrade prints it as ' +
195
202
  '`Regenerate with: <command>` and lists it in `commands`.',
196
203
  },
204
+ {
205
+ type: 'prose',
206
+ text:
207
+ 'A protected file a codemod cannot parse, such as a vendored bundle written for another toolchain, cannot need a ' +
208
+ 'change the codemod can prove, and upgrade never writes it. upgrade skips it, lists it under ' +
209
+ '`declinedCandidates` with the parse error and where it occurred, and carries on; on its own it does not fail the run. ' +
210
+ 'If another codemod in the same upgrade still requires a change to that file (the 0.6.0 theme selector migration, for one, ' +
211
+ 'adds a TODO comment above a selector it cannot parse), the file is listed once, under `protectedFiles`, and the run is ' +
212
+ 'incomplete as for any protected file. A file upgrade owns that does not parse still fails the run with ERR_CODEMOD_FAILED.',
213
+ },
214
+ {type: 'heading', level: 3, text: 'A failed codemod'},
215
+ {
216
+ type: 'prose',
217
+ text:
218
+ 'When a codemod or a `hooks.postCodemod` command fails, upgrade still makes every other change, exits 1 with ERR_CODEMOD_FAILED, and does not refresh the agent docs. ' +
219
+ 'With --json, the result is the usual error, `{"error": ..., "code": "ERR_CODEMOD_FAILED"}`, plus a `receipt`: the same fields a finished run returns, with `complete: false`, ' +
220
+ 'each failure in `errors`, and every file upgrade changed (or would change) in `modifiedFiles`, so a script can review, keep, or revert them. ' +
221
+ 'An error that stops the run after codemods have written files, such as an astryx.config that fails validation, carries a `receipt` too. ' +
222
+ 'Rerun past a failed codemod with --skip-codemod.',
223
+ },
197
224
  ],
198
225
  };
@@ -199,6 +199,35 @@ describe('upgrade protected-file contract', () => {
199
199
  });
200
200
  });
201
201
 
202
+ it('keeps the error and adds the receipt when a hook leaves a protection declaration unreadable', () => {
203
+ seed();
204
+ write(
205
+ 'astryx.config.mjs',
206
+ `export default {hooks: {postCodemod: [{name: 'regenerate', buildCommand: () => ({command: process.execPath, args: ['-e', ${JSON.stringify("require('node:fs').writeFileSync('.hgignore', 'syntax: regexp\\n[bad\\n')")}]})}]}};\n`,
207
+ );
208
+
209
+ const applied = run([...ARGS, '--apply']);
210
+
211
+ expect(applied.status).toBe(1);
212
+ expect(applied.envelope).not.toHaveProperty('type');
213
+ expect(applied.envelope).toMatchObject({
214
+ code: 'ERR_CODEMOD_PROTECTION_SOURCE',
215
+ error: expect.stringContaining('.hgignore'),
216
+ receipt: {
217
+ complete: false,
218
+ errorCode: 'ERR_CODEMOD_PROTECTION_SOURCE',
219
+ modifiedFiles: ['src/owned.tsx'],
220
+ protectedFiles: [
221
+ expect.objectContaining({file: 'generated/panel.tsx'}),
222
+ ],
223
+ errors: [expect.objectContaining({codemod: 'file-protection'})],
224
+ },
225
+ });
226
+ expect(fs.readFileSync(path.join(root, 'src/owned.tsx'), 'utf8')).toContain(
227
+ 'minSize: 200',
228
+ );
229
+ });
230
+
202
231
  it('runs declared regeneration and clears a generated-file block after reevaluation', () => {
203
232
  seed({hook: true});
204
233
 
@@ -226,4 +255,150 @@ describe('upgrade protected-file contract', () => {
226
255
  expect(second.envelope.data.complete).toBe(true);
227
256
  expect(second.envelope.data.filesChanged).toBe(0);
228
257
  });
258
+
259
+ it('skips a vendored file that does not parse and completes the upgrade', () => {
260
+ seed();
261
+ write('.gitattributes', 'vendor/** linguist-vendored\n');
262
+ const bundle =
263
+ "/* minified */ import {useResizable} from '@astryxdesign/core';\n" +
264
+ 'export const x = useResizable({minSizePx: 200;\n';
265
+ write('vendor/bundle.js', bundle);
266
+ rmGenerated();
267
+
268
+ const applied = run([...ARGS, '--apply']);
269
+
270
+ expect(applied.status, applied.stderr).toBe(0);
271
+ expect(applied.envelope).toMatchObject({
272
+ type: 'upgrade.run',
273
+ data: {
274
+ complete: true,
275
+ modifiedFiles: ['src/owned.tsx'],
276
+ protectedFiles: [],
277
+ declinedCandidates: [
278
+ {
279
+ file: 'vendor/bundle.js',
280
+ location: '2:46',
281
+ reason:
282
+ 'unparseable protected file (vendored): Unexpected token, expected ","',
283
+ },
284
+ ],
285
+ },
286
+ });
287
+ expect(applied.envelope.data.errors ?? []).toEqual([]);
288
+ expect(fs.readFileSync(path.join(root, 'src/owned.tsx'), 'utf8')).toContain(
289
+ 'minSize: 200',
290
+ );
291
+ expect(fs.readFileSync(path.join(root, 'vendor/bundle.js'), 'utf8')).toBe(
292
+ bundle,
293
+ );
294
+
295
+ const text = spawnSync(process.execPath, [CLI, 'upgrade', ...ARGS], {
296
+ cwd: root,
297
+ encoding: 'utf8',
298
+ timeout: 60_000,
299
+ env: {...process.env, FORCE_COLOR: '0', CI: ''},
300
+ });
301
+ expect(text.status, text.stderr).toBe(0);
302
+ expect(`${text.stdout}${text.stderr}`).toContain(
303
+ '1 protected file was skipped because it does not parse',
304
+ );
305
+ const declinedLine = `${text.stdout}${text.stderr}`
306
+ .split('\n')
307
+ .find(line => line.includes('vendor/bundle.js:2:46'));
308
+ expect(declinedLine).toMatch(/^ {2}vendor\/bundle\.js:2:46 - /);
309
+ // cli-surface output is plain ASCII.
310
+ expect(declinedLine).toMatch(/^[\x20-\x7e]*$/);
311
+ });
312
+
313
+ it('still fails when an owned file does not parse', () => {
314
+ seed();
315
+ write(
316
+ 'lib/broken.js',
317
+ "import {useResizable} from '@astryxdesign/core';\n" +
318
+ 'export const x = useResizable({minSizePx: 200;\n',
319
+ );
320
+ rmGenerated();
321
+
322
+ const applied = run([...ARGS, '--apply']);
323
+
324
+ expect(applied.status).toBe(1);
325
+ expect(applied.envelope).toMatchObject({code: 'ERR_CODEMOD_FAILED'});
326
+ });
327
+
328
+ it('reports a stylesheet the 0.6 and 0.7 theme codemods both need once, as protected', () => {
329
+ write('package.json', JSON.stringify({name: 'consumer', private: true}));
330
+ write(
331
+ 'node_modules/@astryxdesign/core/package.json',
332
+ JSON.stringify({name: '@astryxdesign/core', version: CLI_VERSION}),
333
+ );
334
+ write('.gitattributes', 'vendor/** linguist-vendored\n');
335
+ write('vendor/bundle.css', 'a:: { color: red; }\n');
336
+
337
+ const result = run(['--from', '0.5.4', '--path', '.']);
338
+ const text = spawnSync(
339
+ process.execPath,
340
+ [CLI, 'upgrade', '--from', '0.5.4', '--path', '.'],
341
+ {
342
+ cwd: root,
343
+ encoding: 'utf8',
344
+ timeout: 60_000,
345
+ env: {...process.env, FORCE_COLOR: '0', CI: ''},
346
+ },
347
+ );
348
+ const output = `${text.stdout}${text.stderr}`;
349
+ expect(text.status).toBe(1);
350
+ expect(output).toContain('ERR_CODEMOD_PROTECTED');
351
+ expect(output).toMatch(/^ {2}vendor\/bundle\.css — /m);
352
+ expect(output).not.toContain('skipped because');
353
+ expect(output).not.toContain('unparseable protected file');
354
+
355
+ expect(result.status).toBe(1);
356
+ expect(result.envelope).toMatchObject({
357
+ type: 'upgrade.run',
358
+ data: {
359
+ complete: false,
360
+ errorCode: 'ERR_CODEMOD_PROTECTED',
361
+ protectedFiles: [expect.objectContaining({file: 'vendor/bundle.css'})],
362
+ declinedCandidates: [],
363
+ },
364
+ });
365
+ });
366
+
367
+ it('lists a generated file the hook regenerates into bytes that do not parse', () => {
368
+ seed();
369
+ const broken =
370
+ "// @generated\nimport {useResizable} from '@astryxdesign/core';\n" +
371
+ 'export const usePanel = () => useResizable({minSizePx: 200;\n';
372
+ write(
373
+ 'astryx.config.mjs',
374
+ `export default {hooks: {postCodemod: [{name: 'regenerate', buildCommand: () => ({command: process.execPath, args: ['-e', ${JSON.stringify(`require('node:fs').writeFileSync('generated/panel.tsx', ${JSON.stringify(broken)})`)}]})}]}};\n`,
375
+ );
376
+
377
+ const applied = run([...ARGS, '--apply']);
378
+
379
+ expect(applied.status, applied.stderr).toBe(0);
380
+ expect(applied.envelope).toMatchObject({
381
+ type: 'upgrade.run',
382
+ data: {
383
+ complete: true,
384
+ protectedFiles: [],
385
+ declinedCandidates: [
386
+ {
387
+ file: 'generated/panel.tsx',
388
+ location: expect.stringMatching(/^3:\d+$/),
389
+ reason: expect.stringMatching(
390
+ /^unparseable protected file \(generated\): /,
391
+ ),
392
+ },
393
+ ],
394
+ },
395
+ });
396
+ expect(
397
+ fs.readFileSync(path.join(root, 'generated/panel.tsx'), 'utf8'),
398
+ ).toBe(broken);
399
+ });
229
400
  });
401
+
402
+ function rmGenerated() {
403
+ fs.rmSync(path.join(root, 'generated'), {recursive: true, force: true});
404
+ }
@@ -175,6 +175,43 @@ describe('astryx upgrade exit codes', () => {
175
175
  expect(status).toBe(1);
176
176
  expect(envelope.code).toBe('ERR_CODEMOD_FAILED');
177
177
  expect(envelope.error).toMatch(/Post-codemod hook failed/);
178
+ // Additive: the receipt names what the run had already changed.
179
+ expect(envelope).toMatchObject({
180
+ receipt: {
181
+ complete: false,
182
+ errorCode: 'ERR_CODEMOD_FAILED',
183
+ modifiedFiles: ['src/panel.tsx'],
184
+ errors: [
185
+ expect.objectContaining({
186
+ codemod: 'post-codemod-hook',
187
+ error: expect.stringMatching(/Post-codemod hook failed/),
188
+ }),
189
+ ],
190
+ },
191
+ });
192
+ }, SLOW);
193
+
194
+ it('reports what core codemods wrote when astryx.config then fails validation', async () => {
195
+ installPackage('@astryxdesign/core', '0.6.0');
196
+ write(
197
+ 'src/panel.tsx',
198
+ "import {useResizable} from '@astryxdesign/core';\nexport const r = () => useResizable({minSizePx: 200});\n",
199
+ );
200
+ write('astryx.config.mjs', "export default {theme: 'neutral'};\n");
201
+ const {status, envelope} = await upgradeJson(['--from', '0.5.0', '--apply']);
202
+ expect(status).toBe(1);
203
+ expect(envelope).toMatchObject({
204
+ code: 'ERR_INVALID_ARGUMENT',
205
+ receipt: {
206
+ complete: false,
207
+ errorCode: 'ERR_INVALID_ARGUMENT',
208
+ modifiedFiles: ['src/panel.tsx'],
209
+ errors: [expect.objectContaining({codemod: 'config'})],
210
+ },
211
+ });
212
+ expect(fs.readFileSync(path.join(tmpDir, 'src/panel.tsx'), 'utf8')).toContain(
213
+ 'minSize: 200',
214
+ );
178
215
  }, SLOW);
179
216
 
180
217
  it('lists a missing jscodeshift and the refused flag combinations', () => {
@@ -17,6 +17,7 @@ import * as fs from 'node:fs';
17
17
  import * as path from 'node:path';
18
18
  import {Command} from 'commander';
19
19
  import {registerUpgrade} from './upgrade.mjs';
20
+ import {isError} from '../../../api/json/parse.mjs';
20
21
  import {Project} from '../../../foundation/config/project.mjs';
21
22
  import {
22
23
  generateCompressedIndex,
@@ -47,6 +48,7 @@ beforeEach(() => {
47
48
  });
48
49
 
49
50
  afterEach(() => {
51
+ process.exitCode = undefined;
50
52
  process.chdir(originalCwd);
51
53
  fs.rmSync(tmpDir, {recursive: true, force: true});
52
54
  vi.restoreAllMocks();
@@ -298,6 +300,13 @@ describe('upgrade integration error policy (skip + warn)', () => {
298
300
  ]);
299
301
 
300
302
  expect(result.code).toBe('ERR_CODEMOD_FAILED');
303
+ expect(result.receipt).toMatchObject({
304
+ complete: false,
305
+ errorCode: 'ERR_CODEMOD_FAILED',
306
+ agentDocsRefreshed: false,
307
+ modifiedFiles: ['src/index.ts'],
308
+ errors: [expect.objectContaining({codemod: 'post-codemod-hook'})],
309
+ });
301
310
  expect(fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8')).toBe(
302
311
  before,
303
312
  );
@@ -476,3 +485,97 @@ describe('upgrade integration error policy (skip + warn)', () => {
476
485
  expect(out).not.toContain('bar');
477
486
  });
478
487
  });
488
+
489
+ describe('upgrade failure receipt when a codemod fails', () => {
490
+ const codemods = {
491
+ '0.2.0/drop-foo.mjs': `export default {type: 'code', title: 'Drop foo', transform: file => file.source.replace(/foo/g, 'bar')};\n`,
492
+ '0.2.0/fail.mjs': `export default {type: 'code', title: 'Fail on boom', transform: file => { if (file.source.includes('boom')) throw new Error('codemod boom'); return undefined; }};\n`,
493
+ };
494
+
495
+ function scaffold() {
496
+ scaffoldIntegration(codemods);
497
+ writeInstalledCore('0.2.0');
498
+ writeSource();
499
+ fs.writeFileSync(path.join(tmpDir, 'src', 'broken.ts'), 'const boom = 1;\n');
500
+ }
501
+
502
+ const ARGS = ['upgrade', '--from', '0.1.0', '--path', 'src'];
503
+
504
+ it('keeps the error envelope and adds the receipt of what was written', async () => {
505
+ scaffold();
506
+
507
+ const result = await runJson(['--json', ...ARGS, '--apply']);
508
+
509
+ expect(exitCode).toBe(1);
510
+ expect(isError(result)).toBe(true);
511
+ expect(result).not.toHaveProperty('type');
512
+ expect(result).toMatchObject({
513
+ apiVersion: 1,
514
+ code: 'ERR_CODEMOD_FAILED',
515
+ error: 'Upgrade completed with 1 codemod error.',
516
+ receipt: {
517
+ complete: false,
518
+ errorCode: 'ERR_CODEMOD_FAILED',
519
+ filesChanged: 1,
520
+ modifiedFiles: ['src/index.ts'],
521
+ protectedFiles: [],
522
+ errors: [
523
+ {
524
+ file: 'src/broken.ts',
525
+ codemod: '@acme/widgets:fail',
526
+ error: 'codemod boom',
527
+ },
528
+ ],
529
+ },
530
+ });
531
+ expect(fs.readFileSync(path.join(tmpDir, 'src', 'index.ts'), 'utf-8')).toBe(
532
+ 'const bar = 1;\n',
533
+ );
534
+ });
535
+
536
+ it('previews the same receipt in a dry run without writing', async () => {
537
+ scaffold();
538
+
539
+ const result = await runJson(['--json', ...ARGS]);
540
+
541
+ expect(result.code).toBe('ERR_CODEMOD_FAILED');
542
+ expect(result.receipt).toMatchObject({
543
+ complete: false,
544
+ modifiedFiles: ['src/index.ts'],
545
+ errors: [expect.objectContaining({file: 'src/broken.ts'})],
546
+ });
547
+ expect(fs.readFileSync(path.join(tmpDir, 'src', 'index.ts'), 'utf-8')).toBe(
548
+ 'const foo = 1;\n',
549
+ );
550
+ });
551
+
552
+ it('still returns the protected-file receipt when a protected file remains', async () => {
553
+ scaffold();
554
+ fs.writeFileSync(
555
+ path.join(tmpDir, 'src', 'gen.ts'),
556
+ '// @generated\nconst foo = 2;\n',
557
+ );
558
+
559
+ const result = await runJson(['--json', ...ARGS, '--apply']);
560
+
561
+ expect(result).toMatchObject({
562
+ type: 'upgrade.run',
563
+ data: {
564
+ complete: false,
565
+ errorCode: 'ERR_CODEMOD_PROTECTED',
566
+ protectedFiles: [expect.objectContaining({file: 'src/gen.ts'})],
567
+ errors: [expect.objectContaining({file: 'src/broken.ts'})],
568
+ },
569
+ });
570
+ });
571
+
572
+ it('keeps the human output and exit status in text mode', async () => {
573
+ scaffold();
574
+
575
+ await runJson([...ARGS, '--apply']);
576
+
577
+ expect(process.exitCode).toBe(1);
578
+ expect(logCalls.join('\n')).toMatch(/Upgrade failed/);
579
+ expect(logCalls.join('\n')).not.toMatch(/"receipt"/);
580
+ });
581
+ });
@@ -57,8 +57,15 @@ export function registerUpgrade(program) {
57
57
  // already printed the error before throwing.
58
58
  logger.setSilent(json);
59
59
  if (e instanceof AstryxError) {
60
- if (json) jsonError(e.message, undefined, e.code);
61
- else {
60
+ if (json) {
61
+ // A failed migration still names the files it already changed.
62
+ jsonError(
63
+ e.message,
64
+ undefined,
65
+ e.code,
66
+ /** @type {any} */ (e).receipt,
67
+ );
68
+ } else {
62
69
  // The logger was silent only for --list; replay the error there.
63
70
  // Non-list failures were already printed by the API.
64
71
  if (isList) logger.error(e.message);
@@ -34,6 +34,13 @@ export interface CLIError {
34
34
  error: string;
35
35
  code: ErrorCode;
36
36
  suggestions?: Suggestion[];
37
+ /**
38
+ * What the command had already done when it failed, present only on errors
39
+ * from a command that changes files before it can fail (for example the
40
+ * `upgrade.run` data of a failed `astryx upgrade`). The error is still an
41
+ * error: branch on `code`.
42
+ */
43
+ receipt?: Record<string, unknown>;
37
44
  }
38
45
 
39
46
  /** Returned by the fallback hook for commands without --json support. */
@@ -150,7 +150,8 @@ export const doc = {
150
150
  },
151
151
  {
152
152
  value: 'ERR_CODEMOD_FAILED',
153
- description: 'One or more codemods failed during an upgrade run.',
153
+ description:
154
+ 'A codemod or post-codemod hook failed during an upgrade run; the error carries a `receipt` that lists the files the run already changed.',
154
155
  },
155
156
  {
156
157
  value: 'ERR_CODEMOD_PROTECTED',
@@ -282,7 +283,7 @@ export const doc = {
282
283
  {
283
284
  value: 'ERR_VERSIONS_UNAVAILABLE',
284
285
  description:
285
- 'Nothing could answer this run, and nothing was written: the project\'s own CLI could not start and nothing else could answer, or the Core a command needs outside a project could not be installed.',
286
+ "Nothing could answer this run, and nothing was written: the project's own CLI could not start and nothing else could answer, or the Core a command needs outside a project could not be installed.",
286
287
  },
287
288
  {
288
289
  value: 'ERR_PROJECT_REQUIRED',
@@ -172,7 +172,7 @@ export const ERROR_CODES = Object.freeze({
172
172
  ERR_UNKNOWN_FEATURE: 'ERR_UNKNOWN_FEATURE',
173
173
  /** A `--codemod` value did not match any registered codemod (upgrade). */
174
174
  ERR_UNKNOWN_CODEMOD: 'ERR_UNKNOWN_CODEMOD',
175
- /** One or more codemods failed during an upgrade run. */
175
+ /** One or more codemods, or a post-codemod hook, failed during an upgrade run. */
176
176
  ERR_CODEMOD_FAILED: 'ERR_CODEMOD_FAILED',
177
177
  /** A required codemod change remains blocked by a protected consumer file. */
178
178
  ERR_CODEMOD_PROTECTED: 'ERR_CODEMOD_PROTECTED',