@astryxdesign/cli 0.6.5-canary.f261d2f → 0.6.5-canary.f27f749

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 (76) hide show
  1. package/README.md +14 -13
  2. package/api/error.d.mts +22 -0
  3. package/api/error.mjs +42 -0
  4. package/api/integration/add-contribution.d.mts +2 -1
  5. package/api/integration/add-contribution.mjs +7 -3
  6. package/api/integration/add-theme.mjs +243 -22
  7. package/api/integration/add-theme.test.mjs +213 -0
  8. package/api/integration/authoring-checks.mjs +10 -7
  9. package/api/integration/authoring-checks.type.d.mts +8 -0
  10. package/api/integration/authoring-checks.type.mjs +7 -3
  11. package/api/integration/integration-authoring.type.d.mts +4 -1
  12. package/api/integration/integration-authoring.type.mjs +6 -1
  13. package/api/integration/integrationAdd.doc.mjs +6 -0
  14. package/api/integration/integrationAddTheme.doc.mjs +10 -0
  15. package/api/integration/integrationComponentConflicts.doc.mjs +1 -1
  16. package/api/integration/integrationDocConflicts.doc.mjs +1 -1
  17. package/api/integration/integrationTemplateConflicts.doc.mjs +1 -1
  18. package/api/integration/validate-integration.d.mts +4 -2
  19. package/api/integration/validate-integration.mjs +7 -2
  20. package/api/integration/validate-integration.test.mjs +55 -0
  21. package/api/integration/validate-integration.type.d.mts +5 -0
  22. package/api/integration/validate-integration.type.mjs +5 -1
  23. package/api/integration/validateIntegration.doc.mjs +1 -1
  24. package/api/layout/expand/expand.mjs +12 -7
  25. package/api/layout/expand/expand.receipt.test.mjs +74 -0
  26. package/api/layout/layout.type.d.mts +1 -0
  27. package/api/layout/layout.type.mjs +1 -0
  28. package/api/layout/layoutExpand.doc.mjs +1 -1
  29. package/api/swizzle/copy/copy.mjs +66 -3
  30. package/api/swizzle/swizzle.doc.mjs +4 -0
  31. package/api/template/copy/copy.mjs +14 -8
  32. package/api/template/copy/copy.receipt.test.mjs +77 -0
  33. package/api/template/show/show.mjs +15 -4
  34. package/api/template/show/show.test.mjs +76 -0
  35. package/api/template/template.d.mts +1 -1
  36. package/api/template/template.doc.mjs +6 -2
  37. package/api/template/template.mjs +1 -0
  38. package/api/template/template.type.d.mts +2 -0
  39. package/api/template/template.type.mjs +2 -0
  40. package/api/theme/build/build.d.mts +24 -0
  41. package/api/theme/build/build.mjs +235 -8
  42. package/api/theme/build/build.project-core.test.mjs +165 -0
  43. package/api/upgrade/run/run.mjs +20 -3
  44. package/api/upgrade/run/run.test.mjs +45 -1
  45. package/api/upgrade/upgrade.doc.mjs +1 -1
  46. package/api/upgrade/upgrade.type.d.mts +1 -0
  47. package/api/upgrade/upgrade.type.mjs +1 -0
  48. package/assets/docs/icons.doc.mjs +1 -0
  49. package/assets/templates/themes/butter/icons.tsx +2 -0
  50. package/assets/templates/themes/chocolate/icons.tsx +2 -0
  51. package/assets/templates/themes/gothic/icons.tsx +2 -0
  52. package/assets/templates/themes/matcha/icons.tsx +2 -0
  53. package/assets/templates/themes/neutral/icons.tsx +2 -0
  54. package/assets/templates/themes/stone/icons.tsx +2 -0
  55. package/assets/templates/themes/y2k/icons.tsx +2 -0
  56. package/clients/cli/commands/doctor.mjs +4 -4
  57. package/clients/cli/commands/integration-add.doc.mjs +10 -0
  58. package/clients/cli/commands/integration-authoring.test.mjs +12 -2
  59. package/clients/cli/commands/integration.mjs +3 -1
  60. package/clients/cli/commands/layout-expand.doc.mjs +3 -1
  61. package/clients/cli/commands/layout.expand-receipt.test.mjs +94 -0
  62. package/clients/cli/commands/layout.mjs +16 -0
  63. package/clients/cli/commands/template.copy-receipt.test.mjs +60 -0
  64. package/clients/cli/commands/template.mjs +19 -5
  65. package/clients/cli/commands/template.show-media.test.mjs +62 -0
  66. package/clients/cli/commands/upgrade.ascii-output.test.mjs +14 -0
  67. package/clients/cli/commands/write-failure.test.mjs +175 -0
  68. package/clients/cli/lib/manifest.mjs +44 -165
  69. package/clients/cli/lib/manifest.test.mjs +98 -7
  70. package/foundation/discovery/template-adapter.d.mts +13 -0
  71. package/foundation/discovery/template-adapter.fixture-refs.test.mjs +37 -1
  72. package/foundation/discovery/template-adapter.mjs +16 -1
  73. package/foundation/doc-compiler/doc-loads.test.mjs +2 -2
  74. package/foundation/response/response-types.doc.d.mts +5 -5
  75. package/foundation/response/response-types.doc.mjs +13 -13
  76. package/package.json +9 -9
@@ -31,6 +31,7 @@ import {
31
31
  Menu,
32
32
  MoreHorizontal,
33
33
  Search,
34
+ Upload,
34
35
  ArrowUp,
35
36
  ArrowDown,
36
37
  ArrowUpDown,
@@ -67,6 +68,7 @@ export const stoneIconRegistry: IconRegistry = {
67
68
  menu: <Menu {...iconProps} />,
68
69
  moreHorizontal: <MoreHorizontal {...iconProps} />,
69
70
  search: <Search {...iconProps} />,
71
+ upload: <Upload {...iconProps} />,
70
72
  arrowUp: <ArrowUp {...iconProps} />,
71
73
  arrowDown: <ArrowDown {...iconProps} />,
72
74
  arrowsUpDown: <ArrowUpDown {...iconProps} />,
@@ -21,6 +21,7 @@ import {
21
21
  Menu,
22
22
  MoreHorizontal,
23
23
  Search,
24
+ Upload,
24
25
  ArrowUp,
25
26
  ArrowDown,
26
27
  ArrowUpDown,
@@ -57,6 +58,7 @@ export const y2kIconRegistry: IconRegistry = {
57
58
  menu: <Menu {...iconProps} />,
58
59
  moreHorizontal: <MoreHorizontal {...iconProps} />,
59
60
  search: <Search {...iconProps} />,
61
+ upload: <Upload {...iconProps} />,
60
62
  arrowUp: <ArrowUp {...iconProps} />,
61
63
  arrowDown: <ArrowDown {...iconProps} />,
62
64
  arrowsUpDown: <ArrowUpDown {...iconProps} />,
@@ -258,10 +258,10 @@ async function runProjectDoctor(program) {
258
258
  async function runIntegrationValidation(program, pkg) {
259
259
  const result = await validateIntegration(pkg);
260
260
  if (program.opts().json) jsonOut(result);
261
- else if (result.data.name === null) {
261
+ else if (!result.data.validated) {
262
262
  emit(
263
263
  text(
264
- 'No astryx.integration.* found next to package.json. ' +
264
+ 'Nothing was validated: no astryx.integration.* found next to package.json. ' +
265
265
  'To validate an installed integration: astryx doctor integration validate <package>',
266
266
  ),
267
267
  );
@@ -284,10 +284,10 @@ async function runAuthoringCheck(program, pkg, kind) {
284
284
  : await integrationDocConflicts(pkg);
285
285
 
286
286
  if (program.opts().json) jsonOut(result);
287
- else if (result.data.name === null) {
287
+ else if (!result.data.validated) {
288
288
  emit(
289
289
  text(
290
- 'No astryx.integration.* found next to package.json. ' +
290
+ 'Nothing was checked: no astryx.integration.* found next to package.json. ' +
291
291
  `To check an installed integration: astryx doctor integration ${kind} <package>`,
292
292
  ),
293
293
  );
@@ -56,6 +56,12 @@ export const doc = {
56
56
  description:
57
57
  "Namespace of this package to place the doc in, as a guide in its `guides` slot; writes the namespace doc when it is missing, and declares the CLI that reads it as an optional `@astryxdesign/cli` peer. Only valid for doc, and not with --replaces or --extends",
58
58
  },
59
+ {
60
+ flag: '--from <theme>',
61
+ param: 'options.from',
62
+ description:
63
+ 'Existing theme slug to fork as a starting point instead of a blank scaffold; the new theme copies the base and has no link back. Only valid for theme',
64
+ },
59
65
  {
60
66
  flag: '--to <version>',
61
67
  param: 'options.to',
@@ -102,6 +108,10 @@ export const doc = {
102
108
  cli: "astryx integration add agent-doc 'Run acme verify before finishing.'",
103
109
  },
104
110
  {label: 'Add a source theme', cli: 'astryx integration add theme ocean'},
111
+ {
112
+ label: 'Fork an existing theme',
113
+ cli: 'astryx integration add theme ocean --from neutral',
114
+ },
105
115
  ],
106
116
  exitCodes: [
107
117
  {code: 0, when: 'the contribution is written or the dry run succeeds'},
@@ -174,11 +174,21 @@ describe('integration authoring CLI', () => {
174
174
  expect(text.stdout).toBe(verifyText.stdout);
175
175
  expect(text.stderr).toContain('`integration pack --check` is deprecated');
176
176
  expect(text.stderr).toContain('astryx integration verify');
177
- // Without --check it fails, as it did, and names both spellings.
177
+ // Without --check it fails, as it did, and points only at the new name:
178
+ // suggesting `--check` would send people to the deprecated spelling.
178
179
  const bare = await runCli(['integration', 'pack'], tmpDir);
179
180
  expect(bare.status).not.toBe(0);
180
- expect(bare.stderr).toContain('--check');
181
+ expect(bare.stderr).toContain(
182
+ '`integration pack` is now `integration verify`',
183
+ );
181
184
  expect(bare.stderr).toContain('astryx integration verify');
185
+ expect(bare.stderr).toContain('npm pack');
186
+ expect(bare.stderr).not.toContain('--check');
187
+ const bareJson = await runCli(['--json', 'integration', 'pack'], tmpDir);
188
+ expect(parseEnvelope(bareJson.stdout)).toMatchObject({
189
+ code: 'ERR_INVALID_ARGUMENT',
190
+ error: expect.stringContaining('astryx integration verify'),
191
+ });
182
192
  // Help lists it, marked deprecated: nothing is hidden.
183
193
  const help = await runCli(['integration', '--help'], tmpDir);
184
194
  expect(help.stdout).toMatch(
@@ -115,6 +115,7 @@ export function registerIntegration(program) {
115
115
  extends: options.extends,
116
116
  parent: options.parent,
117
117
  to: options.to,
118
+ from: options.from,
118
119
  });
119
120
  } catch (error) {
120
121
  const err =
@@ -168,8 +169,9 @@ export function registerIntegration(program) {
168
169
  fn: integrationPackCheckFn,
169
170
  action: async options => {
170
171
  if (!options.check) {
172
+ // One way forward: the new name. `npm pack` is what builds a tarball.
171
173
  return cliError(
172
- 'Pass --check to verify the integration tarball, or run `astryx integration verify`.',
174
+ '`integration pack` is now `integration verify`: run `astryx integration verify` to check the package the way npm will publish it. To build the tarball, run `npm pack`.',
173
175
  {code: ERROR_CODES.ERR_INVALID_ARGUMENT},
174
176
  );
175
177
  }
@@ -18,7 +18,9 @@ export const doc = {
18
18
  description:
19
19
  'Parses and validates a compressed XLE/XLO expression, then expands it into ' +
20
20
  'ready-to-use XDS TSX, routing children into slots, scaffolding typed useState for ' +
21
- 'interactive controls, and splicing referenced blocks. Writes to a path, or returns the code.',
21
+ 'interactive controls, and splicing referenced blocks. Writes to a path, or returns the code. ' +
22
+ 'Astryx demo media in a spliced block becomes a placeholder, and the output says how many ' +
23
+ 'references were replaced (as a closing line comment when it prints the code).',
22
24
  fn: 'layoutExpand',
23
25
  args: [
24
26
  {
@@ -0,0 +1,94 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file `astryx layout expand` tells the caller, in JSON and in text, when demo
5
+ * media in a spliced template block was replaced with placeholders. Printed
6
+ * code stays verbatim and valid TSX: the disclosure follows it as a comment.
7
+ */
8
+
9
+ import {describe, it, expect, beforeEach, afterEach} from 'vitest';
10
+ import * as fs from 'node:fs';
11
+ import * as path from 'node:path';
12
+ import ts from 'typescript';
13
+ import {runCli} from '../../../test-utils/run-cli.mjs';
14
+ import {discoverTemplates} from '../../../api/template/template.mjs';
15
+
16
+ const SLOW = 60_000;
17
+ const DISCLOSURE = /demo media/i;
18
+
19
+ /** @param {string} name */
20
+ const hintKey = name => name.toLowerCase().replace(/[^a-z0-9]/g, '');
21
+
22
+ /** @param {string} source */
23
+ const tsxErrors = source =>
24
+ /** @type {any} */ (
25
+ ts.createSourceFile('out.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX)
26
+ ).parseDiagnostics.map((/** @type {ts.Diagnostic} */ d) =>
27
+ ts.flattenDiagnosticMessageText(d.messageText, ' '),
28
+ );
29
+
30
+ /** A `{hint}` for a template block whose source carries demo media. */
31
+ async function mediaBlockHint() {
32
+ const blocks = /** @type {Array<{dirName: string, type: string, filePath: string}>} */ (
33
+ await discoverTemplates()
34
+ ).filter(t => t.type === 'block' && t.filePath && fs.existsSync(t.filePath));
35
+ const seen = new Map();
36
+ for (const t of blocks) seen.set(hintKey(t.dirName), (seen.get(hintKey(t.dirName)) ?? 0) + 1);
37
+ const found = blocks.find(
38
+ t =>
39
+ seen.get(hintKey(t.dirName)) === 1 &&
40
+ /\/template-assets\/[\w.-]+\.\w+/.test(fs.readFileSync(t.filePath, 'utf-8')),
41
+ );
42
+ if (!found) throw new Error('no template block carries demo media');
43
+ return hintKey(found.dirName);
44
+ }
45
+
46
+ describe('layout expand discloses replaced demo media', () => {
47
+ let cwd;
48
+ beforeEach(() => {
49
+ // Inside the workspace so @astryxdesign/core resolves.
50
+ cwd = fs.mkdtempSync(path.join(process.cwd(), '.xle-media-receipt-'));
51
+ });
52
+ afterEach(() => fs.rmSync(cwd, {recursive: true, force: true}));
53
+
54
+ it('--json carries demoMediaReplaced; the text receipt states it for the written file', async () => {
55
+ const expr = `V > {${await mediaBlockHint()}}`;
56
+ const json = await runCli(['layout', 'expand', expr, './a', '--json'], cwd);
57
+ expect(json.status).toBe(0);
58
+ const {data} = JSON.parse(json.stdout);
59
+ expect(data.demoMediaReplaced).toBeGreaterThan(0);
60
+
61
+ const human = await runCli(['layout', 'expand', expr, './b'], cwd);
62
+ expect(human.status).toBe(0);
63
+ expect(human.stdout).toContain(
64
+ `Replaced ${data.demoMediaReplaced} Astryx demo media reference`,
65
+ );
66
+ expect(human.stdout).toContain(path.join('b', 'GeneratedLayout.tsx'));
67
+ }, SLOW);
68
+
69
+ it('prints the code verbatim, then states the count in a comment that keeps it valid TSX', async () => {
70
+ const expr = `V > {${await mediaBlockHint()}}`;
71
+ const {data} = JSON.parse((await runCli(['layout', 'expand', expr, '--json'], cwd)).stdout);
72
+
73
+ const human = await runCli(['layout', 'expand', expr], cwd);
74
+ expect(human.status).toBe(0);
75
+ expect(human.stdout.startsWith(data.code)).toBe(true);
76
+ expect(human.stdout.slice(data.code.length).trim()).toMatch(
77
+ new RegExp(`^// Replaced ${data.demoMediaReplaced} Astryx demo media references? in the code above: [^\\n]+$`),
78
+ );
79
+ expect(tsxErrors(human.stdout)).toEqual([]);
80
+ }, SLOW);
81
+
82
+ it('says nothing about demo media when none was replaced', async () => {
83
+ const json = await runCli(['layout', 'expand', 'V > B"Save"', '--json'], cwd);
84
+ const {data} = JSON.parse(json.stdout);
85
+ expect(data.demoMediaReplaced).toBe(0);
86
+
87
+ const written = await runCli(['layout', 'expand', 'V > B"Save"', './a'], cwd);
88
+ expect(written.status).toBe(0);
89
+ expect(written.stdout).not.toMatch(DISCLOSURE);
90
+ const printed = await runCli(['layout', 'expand', 'V > B"Save"'], cwd);
91
+ expect(printed.status).toBe(0);
92
+ expect(printed.stdout).toBe(`${data.code}\n`);
93
+ }, SLOW);
94
+ });
@@ -120,6 +120,20 @@ async function readExpression(expr, options = {}) {
120
120
  return expr ?? '';
121
121
  }
122
122
 
123
+ /**
124
+ * The disclosure for demo media replaced in spliced template blocks, or '' when
125
+ * none was. After printed code it is a line comment, so piped output stays TSX.
126
+ * @param {LayoutExpandResponse['data']} data
127
+ * @returns {string}
128
+ */
129
+ function demoMediaNotice({demoMediaReplaced, written}) {
130
+ if (demoMediaReplaced === 0) return '';
131
+ const notice =
132
+ `Replaced ${demoMediaReplaced} Astryx demo media reference${demoMediaReplaced === 1 ? '' : 's'} in ${written ?? 'the code above'}: ` +
133
+ 'images now show a neutral placeholder and videos have an empty source. Supply your own media there.';
134
+ return written ? notice : `// ${notice}`;
135
+ }
136
+
123
137
  /**
124
138
  * @param {import('commander').Command} program
125
139
  */
@@ -181,6 +195,8 @@ export function registerLayout(program) {
181
195
  // Raw expanded TSX (no target path) — preformatted, emitted verbatim.
182
196
  out.push(code(result.data.code));
183
197
  }
198
+ const mediaNotice = demoMediaNotice(result.data);
199
+ if (mediaNotice) out.push(text(mediaNotice));
184
200
  emit(...out);
185
201
  return NO_RESULT_SET;
186
202
  },
@@ -0,0 +1,60 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file `astryx template <name> <path>` tells the caller, in JSON and in text,
5
+ * when demo media in the copied file was replaced with placeholders.
6
+ */
7
+
8
+ import {describe, it, expect, beforeEach, afterEach} from 'vitest';
9
+ import * as fs from 'node:fs';
10
+ import * as os from 'node:os';
11
+ import * as path from 'node:path';
12
+ import {runCli} from '../../../test-utils/run-cli.mjs';
13
+ import {discoverTemplates} from '../../../api/template/template.mjs';
14
+
15
+ const SLOW = 60_000;
16
+
17
+ /** A page template whose source carries demo media, and one that carries none. */
18
+ async function pickPages() {
19
+ const pages = /** @type {Array<{dirName: string, type: string, filePath: string}>} */ (
20
+ await discoverTemplates()
21
+ ).filter(t => t.type === 'page' && fs.existsSync(t.filePath));
22
+ const hasMedia = (/** @type {{filePath: string}} */ t) =>
23
+ /\/template-assets\/[\w.-]+\.\w+/.test(fs.readFileSync(t.filePath, 'utf-8'));
24
+ const withMedia = pages.find(hasMedia);
25
+ const without = pages.find(t => !hasMedia(t));
26
+ if (!withMedia || !without) throw new Error('catalog lacks a page with and without demo media');
27
+ return {withMedia: withMedia.dirName, without: without.dirName};
28
+ }
29
+
30
+ describe('template copy receipt discloses replaced demo media', () => {
31
+ let dir;
32
+ beforeEach(() => {
33
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tmpl-receipt-cli-'));
34
+ });
35
+ afterEach(() => fs.rmSync(dir, {recursive: true, force: true}));
36
+
37
+ it('--json carries demoMediaReplaced and the text states the same count', async () => {
38
+ const {withMedia} = await pickPages();
39
+ const json = await runCli(['template', withMedia, './a', '--json'], dir);
40
+ expect(json.status).toBe(0);
41
+ const {data} = JSON.parse(json.stdout);
42
+ expect(data.demoMediaReplaced).toBeGreaterThan(0);
43
+
44
+ const human = await runCli(['template', withMedia, './b'], dir);
45
+ expect(human.status).toBe(0);
46
+ expect(human.stdout).toContain(
47
+ `Replaced ${data.demoMediaReplaced} Astryx demo media reference`,
48
+ );
49
+ expect(human.stdout).toContain('b/page.tsx');
50
+ }, SLOW);
51
+
52
+ it('says nothing about media when none was replaced', async () => {
53
+ const {without} = await pickPages();
54
+ const json = await runCli(['template', without, './a', '--json'], dir);
55
+ expect(JSON.parse(json.stdout).data.demoMediaReplaced).toBe(0);
56
+ const human = await runCli(['template', without, './b'], dir);
57
+ expect(human.status).toBe(0);
58
+ expect(human.stdout).not.toMatch(/demo media/i);
59
+ }, SLOW);
60
+ });
@@ -156,16 +156,30 @@ export function registerTemplate(program) {
156
156
  }
157
157
 
158
158
  case 'template.show': {
159
- // Source must survive piping byte-for-byte.
160
- emit(code(result.data.source));
159
+ // Source must survive piping byte-for-byte, so the note about
160
+ // replaced demo media goes to stderr, in the copy receipt's words.
161
+ // (Text mode only: --json returned above with the count in data.)
162
+ const {source, demoMediaReplaced} = result.data;
163
+ emit(code(source));
164
+ if (demoMediaReplaced > 0) {
165
+ console.error(
166
+ `Replaced ${demoMediaReplaced} Astryx demo media reference${demoMediaReplaced === 1 ? '' : 's'}: ` +
167
+ 'images now show a neutral placeholder and videos have an empty source. Supply your own media there.',
168
+ );
169
+ }
161
170
  break;
162
171
  }
163
172
 
164
173
  case 'template.copy': {
174
+ const {outputDir, fileName, demoMediaReplaced} = result.data;
175
+ const file = `${outputDir}/${fileName}`;
165
176
  emit(
166
- text(
167
- `Copied template to ${result.data.outputDir}/${result.data.fileName}`,
168
- ),
177
+ text(`Copied template to ${file}`),
178
+ demoMediaReplaced > 0 &&
179
+ text(
180
+ `Replaced ${demoMediaReplaced} Astryx demo media reference${demoMediaReplaced === 1 ? '' : 's'} in ${file}: ` +
181
+ 'images now show a neutral placeholder and videos have an empty source. Supply your own media there.',
182
+ ),
169
183
  );
170
184
  break;
171
185
  }
@@ -0,0 +1,62 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file `astryx template <name>` says how many demo media references it
5
+ * replaced: in `--json` as `demoMediaReplaced`, and in text on stderr, so that
6
+ * stdout stays exactly the source a copy writes and can be piped into a file.
7
+ */
8
+
9
+ import {describe, it, expect, beforeAll, afterAll} from 'vitest';
10
+ import * as fs from 'node:fs';
11
+ import * as os from 'node:os';
12
+ import * as path from 'node:path';
13
+ import {runCli} from '../../../test-utils/run-cli.mjs';
14
+ import {discoverTemplates} from '../../../api/template/template.mjs';
15
+
16
+ const SLOW = 60_000;
17
+
18
+ /** A page template whose source carries demo media, and one that carries none. */
19
+ async function pickPages() {
20
+ const pages = /** @type {Array<{dirName: string, type: string, filePath: string}>} */ (
21
+ await discoverTemplates()
22
+ ).filter(t => t.type === 'page' && fs.existsSync(t.filePath));
23
+ const hasMedia = (/** @type {{filePath: string}} */ t) =>
24
+ /\/template-assets\/[\w.-]+\.\w+/.test(fs.readFileSync(t.filePath, 'utf-8'));
25
+ const withMedia = pages.find(hasMedia);
26
+ const without = pages.find(t => !hasMedia(t));
27
+ if (!withMedia || !without) throw new Error('catalog lacks a page with and without demo media');
28
+ return {withMedia: withMedia.dirName, without: without.dirName};
29
+ }
30
+
31
+ describe('template show discloses replaced demo media', () => {
32
+ /** @type {string} */
33
+ let dir;
34
+ beforeAll(() => {
35
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tmpl-show-cli-'));
36
+ });
37
+ afterAll(() => fs.rmSync(dir, {recursive: true, force: true}));
38
+
39
+ it('--json carries demoMediaReplaced, and text states it on stderr with stdout left as the source', async () => {
40
+ const {withMedia} = await pickPages();
41
+ const json = await runCli(['template', withMedia, '--type', 'page', '--json'], dir);
42
+ expect(json.status).toBe(0);
43
+ const {data} = JSON.parse(json.stdout);
44
+ expect(data.demoMediaReplaced).toBeGreaterThan(0);
45
+
46
+ const human = await runCli(['template', withMedia, '--type', 'page'], dir);
47
+ expect(human.status).toBe(0);
48
+ expect(human.stdout.trimEnd()).toBe(data.source.trimEnd());
49
+ expect(human.stderr).toContain(
50
+ `Replaced ${data.demoMediaReplaced} Astryx demo media reference`,
51
+ );
52
+ }, SLOW);
53
+
54
+ it('says nothing about media when none was replaced', async () => {
55
+ const {without} = await pickPages();
56
+ const json = await runCli(['template', without, '--type', 'page', '--json'], dir);
57
+ expect(JSON.parse(json.stdout).data.demoMediaReplaced).toBe(0);
58
+ const human = await runCli(['template', without, '--type', 'page'], dir);
59
+ expect(human.status).toBe(0);
60
+ expect(human.stderr).not.toMatch(/demo media/i);
61
+ }, SLOW);
62
+ });
@@ -84,4 +84,18 @@ describe('upgrade human output is ASCII', () => {
84
84
  'minSize: 200',
85
85
  );
86
86
  });
87
+
88
+ // Every fixture above has a real src/, so the completion line for a project
89
+ // whose source is somewhere else was never reached — this suite was green on
90
+ // that path by luck, not by coverage.
91
+ it('reports a source directory that does not exist', async () => {
92
+ fs.rmSync(path.join(tmpDir, 'src'), {recursive: true, force: true});
93
+ fs.mkdirSync(path.join(tmpDir, 'app'), {recursive: true});
94
+ write('app/panel.tsx', 'export const x = 1;\n');
95
+
96
+ expect(await nonAsciiLines(['upgrade', '--from', '0.5.0'])).toEqual([]);
97
+ expect(
98
+ await nonAsciiLines(['upgrade', '--from', '0.5.0', '--apply']),
99
+ ).toEqual([]);
100
+ });
87
101
  });
@@ -0,0 +1,175 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file A write that fails on the filesystem reports ERR_WRITE_FAILED.
5
+ *
6
+ * An unwritable target produced `{"error": "EACCES: permission denied, open
7
+ * '/abs/host/path/readonly/x.tsx'", "code": "ERR_UNKNOWN"}` — the raw Node
8
+ * errno error, with the wrong code and an absolute host path in the message.
9
+ * ERR_WRITE_FAILED is in the frozen registry for exactly this case, and every
10
+ * other Astryx message names its target relative to the project.
11
+ */
12
+
13
+ import {describe, it, expect, beforeEach, afterEach} from 'vitest';
14
+ import * as fs from 'node:fs';
15
+ import * as os from 'node:os';
16
+ import * as path from 'node:path';
17
+ import {fileURLToPath} from 'node:url';
18
+ import {runCli} from '../../../test-utils/run-cli.mjs';
19
+
20
+ const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../../..');
21
+
22
+ // chmod means nothing to root, so the unwritable directory would be writable
23
+ // and the command would succeed. Skip rather than assert something false.
24
+ const asRoot = typeof process.getuid === 'function' && process.getuid() === 0;
25
+
26
+ let dir;
27
+ let readonlyDir;
28
+
29
+ beforeEach(() => {
30
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-write-fail-'));
31
+ fs.writeFileSync(
32
+ path.join(dir, 'package.json'),
33
+ JSON.stringify({
34
+ name: 'scratch',
35
+ version: '1.0.0',
36
+ dependencies: {'@astryxdesign/core': '0.6.3'},
37
+ }),
38
+ );
39
+ fs.mkdirSync(path.join(dir, 'node_modules', '@astryxdesign'), {recursive: true});
40
+ fs.symlinkSync(
41
+ path.join(REPO, 'packages', 'core'),
42
+ path.join(dir, 'node_modules', '@astryxdesign', 'core'),
43
+ 'dir',
44
+ );
45
+ readonlyDir = path.join(dir, 'readonly');
46
+ fs.mkdirSync(readonlyDir);
47
+ fs.chmodSync(readonlyDir, 0o500);
48
+ });
49
+
50
+ afterEach(() => {
51
+ try {
52
+ fs.chmodSync(readonlyDir, 0o700);
53
+ } catch {
54
+ // already gone
55
+ }
56
+ fs.rmSync(dir, {recursive: true, force: true});
57
+ });
58
+
59
+ /** @param {string[]} args */
60
+ const json = async args => {
61
+ const {status, stdout} = await runCli(['--json', ...args], {cwd: dir});
62
+ return {status, body: JSON.parse(stdout)};
63
+ };
64
+
65
+ describe.skipIf(asRoot)('a failed write reports ERR_WRITE_FAILED', () => {
66
+ it('template into an unwritable directory', async () => {
67
+ const {status, body} = await json(['template', 'ai-chat', 'readonly/x.tsx']);
68
+
69
+ expect(status).toBe(1);
70
+ expect(body.code).toBe('ERR_WRITE_FAILED');
71
+ expect(body.error).toContain('readonly/x.tsx');
72
+ expect(body.error).toContain('EACCES');
73
+ // The whole point of the relative form: no absolute host path escapes.
74
+ expect(body.error).not.toContain(dir);
75
+ expect(fs.existsSync(path.join(readonlyDir, 'x.tsx'))).toBe(false);
76
+ });
77
+
78
+ it('swizzle into an unwritable directory', async () => {
79
+ const {status, body} = await json([
80
+ 'swizzle',
81
+ 'Button',
82
+ '--output',
83
+ 'readonly/sub',
84
+ ]);
85
+
86
+ expect(status).toBe(1);
87
+ expect(body.code).toBe('ERR_WRITE_FAILED');
88
+ expect(body.error).toContain('readonly/sub');
89
+ expect(body.error).not.toContain(dir);
90
+ expect(fs.existsSync(path.join(readonlyDir, 'sub'))).toBe(false);
91
+ });
92
+
93
+ it('still writes normally into a writable directory', async () => {
94
+ const {status, body} = await json(['template', 'ai-chat', 'src/page.tsx']);
95
+
96
+ expect(status, JSON.stringify(body).slice(0, 200)).toBe(0);
97
+ expect(body.type).toBe('template.copy');
98
+ expect(fs.existsSync(path.join(dir, 'src', 'page.tsx'))).toBe(true);
99
+ });
100
+ });
101
+
102
+ describe.skipIf(asRoot)('a swizzle that fails part-way undoes what it wrote', () => {
103
+ it('restores replaced files, removes created ones, and says nothing was written', async () => {
104
+ // Learn the component's files, in copy order, from a successful swizzle.
105
+ const probe = await json(['swizzle', 'Button', '--output', 'probe']);
106
+ expect(probe.status, JSON.stringify(probe.body).slice(0, 200)).toBe(0);
107
+ const files = probe.body.data.files;
108
+ expect(files.length).toBeGreaterThan(1);
109
+ const outDir = path.join(dir, 'out', path.basename(probe.body.data.outputDir));
110
+
111
+ // The first file exists (replaceable), the middle ones do not, and the
112
+ // last one is read-only, so --overwrite fails after writing the others.
113
+ const first = files[0];
114
+ const middle = files.slice(1, -1);
115
+ const last = files[files.length - 1];
116
+ fs.mkdirSync(outDir, {recursive: true});
117
+ fs.writeFileSync(path.join(outDir, first), 'before first\n');
118
+ fs.writeFileSync(path.join(outDir, last), 'before last\n');
119
+ fs.chmodSync(path.join(outDir, last), 0o444);
120
+
121
+ const {status, body} = await json([
122
+ 'swizzle',
123
+ 'Button',
124
+ '--output',
125
+ 'out',
126
+ '--overwrite',
127
+ ]);
128
+ fs.chmodSync(path.join(outDir, last), 0o644);
129
+
130
+ expect(status).toBe(1);
131
+ expect(body.code).toBe('ERR_WRITE_FAILED');
132
+ expect(body.error).toContain(last);
133
+ expect(body.error).toContain('Nothing was written.');
134
+ expect(body.error).not.toContain(dir);
135
+ expect(fs.readFileSync(path.join(outDir, first), 'utf8')).toBe('before first\n');
136
+ expect(fs.readFileSync(path.join(outDir, last), 'utf8')).toBe('before last\n');
137
+ for (const file of middle) {
138
+ expect(fs.existsSync(path.join(outDir, file))).toBe(false);
139
+ }
140
+ });
141
+
142
+ it('undoes the copy when a destination cannot be read back', async () => {
143
+ const probe = await json(['swizzle', 'Button', '--output', 'probe']);
144
+ expect(probe.status, JSON.stringify(probe.body).slice(0, 200)).toBe(0);
145
+ const files = probe.body.data.files;
146
+ const outDir = path.join(dir, 'out', path.basename(probe.body.data.outputDir));
147
+
148
+ // A directory where the last file goes: the rollback snapshot cannot read
149
+ // it, and the earlier files are already written when the copy reaches it.
150
+ const first = files[0];
151
+ const middle = files.slice(1, -1);
152
+ const last = files[files.length - 1];
153
+ fs.mkdirSync(path.join(outDir, last), {recursive: true});
154
+ fs.writeFileSync(path.join(outDir, first), 'before first\n');
155
+
156
+ const {status, body} = await json([
157
+ 'swizzle',
158
+ 'Button',
159
+ '--output',
160
+ 'out',
161
+ '--overwrite',
162
+ ]);
163
+
164
+ expect(status).toBe(1);
165
+ expect(body.code).toBe('ERR_WRITE_FAILED');
166
+ expect(body.error).toContain(last);
167
+ expect(body.error).toContain('Nothing was written.');
168
+ expect(body.error).not.toContain(dir);
169
+ expect(fs.readFileSync(path.join(outDir, first), 'utf8')).toBe('before first\n');
170
+ expect(fs.statSync(path.join(outDir, last)).isDirectory()).toBe(true);
171
+ for (const file of middle) {
172
+ expect(fs.existsSync(path.join(outDir, file))).toBe(false);
173
+ }
174
+ });
175
+ });