@astryxdesign/cli 0.6.3-canary.d0d49a4 → 0.6.3-canary.db4e378

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/README.md +86 -72
  2. package/api/build/build.doc.mjs +3 -3
  3. package/api/build/build.test.mjs +14 -3
  4. package/api/build/build.type.d.mts +35 -1
  5. package/api/build/build.type.mjs +24 -3
  6. package/api/build/help/help.d.mts +8 -5
  7. package/api/build/help/help.mjs +56 -6
  8. package/api/component/component.doc.mjs +12 -3
  9. package/api/component/component.mjs +31 -2
  10. package/api/component/component.test.mjs +38 -0
  11. package/api/component/component.type.d.mts +16 -5
  12. package/api/component/component.type.mjs +13 -5
  13. package/api/component/detail/blocks/blocks.d.mts +2 -1
  14. package/api/component/detail/blocks/blocks.mjs +4 -3
  15. package/api/component/list/list.d.mts +0 -5
  16. package/api/component/list/list.mjs +37 -9
  17. package/api/discover/discover.doc.mjs +1 -1
  18. package/api/gap-report/gap-report.doc.mjs +7 -4
  19. package/api/init/init.doc.mjs +4 -0
  20. package/api/init/init.test.mjs +41 -1
  21. package/api/init/remove/remove.mjs +1 -1
  22. package/api/init/run/run.mjs +20 -10
  23. package/api/integration/add-contribution.component-names.test.mjs +120 -0
  24. package/api/integration/add-contribution.mjs +11 -0
  25. package/api/integration/add-contribution.test.mjs +80 -0
  26. package/api/integration/integrationAdd.doc.mjs +7 -4
  27. package/api/integration/integrationAddComponent.doc.mjs +1 -1
  28. package/api/integration/validate-integration.mjs +2 -0
  29. package/api/integration/validate-integration.test.mjs +91 -0
  30. package/api/integration/validateIntegration.doc.mjs +1 -1
  31. package/api/json/envelope-types.test.mjs +76 -0
  32. package/api/json/parseResponse.doc.mjs +2 -2
  33. package/api/layout/expand/expand.mjs +7 -5
  34. package/api/layout/expand/expand.path-safety.test.mjs +53 -0
  35. package/api/layout/grammar/grammar.mjs +2 -1
  36. package/api/layout/layoutExpand.doc.mjs +1 -1
  37. package/api/search/search-return-type.test.mjs +54 -0
  38. package/api/search/search.d.mts +2 -9
  39. package/api/search/search.doc.mjs +5 -1
  40. package/api/search/search.mjs +10 -3
  41. package/api/search/search.test.mjs +34 -0
  42. package/api/swizzle/copy/copy.mjs +28 -11
  43. package/api/swizzle/swizzle.doc.mjs +1 -1
  44. package/api/template/copy/copy.mjs +17 -23
  45. package/api/template/copy/copy.test.mjs +17 -0
  46. package/api/template/template.doc.mjs +2 -1
  47. package/api/theme/add/add.binary.test.mjs +91 -0
  48. package/api/theme/add/add.mjs +20 -3
  49. package/api/theme/add/add.staging.test.mjs +66 -0
  50. package/api/theme/build/build.mjs +114 -37
  51. package/api/theme/build/build.public-component-vars.test.mjs +1 -1
  52. package/api/theme/build/build.receipt-doc.test.mjs +111 -0
  53. package/api/theme/build/font-warning.mjs +3 -3
  54. package/api/theme/build/font-warning.test.mjs +5 -2
  55. package/api/theme/palette/generate/generate.mjs +7 -2
  56. package/api/theme/palette/generate/generate.test.mjs +96 -0
  57. package/api/theme/palette/generate/generator.mjs +8 -1
  58. package/api/theme/palette/generate/generator.test.mjs +10 -0
  59. package/api/theme/template/template.mjs +11 -2
  60. package/api/theme/template/template.test.mjs +15 -0
  61. package/api/theme/themeBuild.doc.mjs +7 -4
  62. package/api/theme/themeTemplate.doc.mjs +4 -1
  63. package/api/upgrade/_adapter.mjs +27 -4
  64. package/api/upgrade/list/list.mjs +2 -1
  65. package/api/upgrade/list/list.test.mjs +73 -0
  66. package/api/upgrade/status/status.mjs +2 -2
  67. package/api/upgrade/upgrade.doc.mjs +2 -1
  68. package/api/upgrade/upgrade.type.d.mts +4 -0
  69. package/api/upgrade/upgrade.type.mjs +1 -0
  70. package/assets/codemods/term-log.mjs +32 -8
  71. package/assets/codemods/term-log.test.mjs +19 -1
  72. package/assets/codemods/transform-prop.mjs +109 -0
  73. package/assets/codemods/transform-prop.test.mjs +95 -0
  74. package/assets/codemods/transforms/v0.0.14/__tests__/rename-status-variants.test.mjs +86 -165
  75. package/assets/codemods/transforms/v0.0.14/rename-status-variants.mjs +72 -210
  76. package/assets/codemods/transforms/v0.1.8/__tests__/rename-avatar-size-scale.test.mjs +83 -115
  77. package/assets/codemods/transforms/v0.1.8/rename-avatar-size-scale.mjs +57 -186
  78. package/assets/codemods/transforms/v0.6.0/__tests__/next-codemods.test.mjs +47 -0
  79. package/assets/codemods/transforms/v0.6.0/rename-resizable-pixel-bounds.mjs +57 -10
  80. package/assets/templates/blocks/components/ScrollableArea/ScrollableAreaInlineRail.doc.mjs +14 -0
  81. package/assets/templates/blocks/components/ScrollableArea/ScrollableAreaInlineRail.tsx +61 -0
  82. package/assets/templates/blocks/components/ScrollableArea/ScrollableAreaOverscrollChaining.doc.mjs +14 -0
  83. package/assets/templates/blocks/components/ScrollableArea/ScrollableAreaOverscrollChaining.tsx +126 -0
  84. package/assets/templates/blocks/components/ScrollableArea/ScrollableAreaShowcase.doc.mjs +15 -0
  85. package/assets/templates/blocks/components/ScrollableArea/ScrollableAreaShowcase.tsx +86 -0
  86. package/assets/templates/blocks/components/ScrollableArea/ScrollableAreaStickyGroupHeaders.doc.mjs +14 -0
  87. package/assets/templates/blocks/components/ScrollableArea/ScrollableAreaStickyGroupHeaders.tsx +99 -0
  88. package/assets/templates/blocks/components/ScrollableArea/ScrollableAreaStickyPassthrough.doc.mjs +14 -0
  89. package/assets/templates/blocks/components/ScrollableArea/ScrollableAreaStickyPassthrough.tsx +122 -0
  90. package/assets/templates/blocks/components/ScrollableArea/ScrollableAreaTwoAxisBoard.doc.mjs +14 -0
  91. package/assets/templates/blocks/components/ScrollableArea/ScrollableAreaTwoAxisBoard.tsx +95 -0
  92. package/assets/templates/pages/table-tree/page.tsx +1704 -0
  93. package/assets/templates/pages/table-tree/template.doc.mjs +12 -0
  94. package/authoring/config/config.doc.mjs +1 -1
  95. package/authoring/config/debug-composition.test.mjs +92 -0
  96. package/authoring/config/type.ts +15 -3
  97. package/clients/cli/command-load-failure.test.mjs +83 -0
  98. package/clients/cli/commands/blog.mjs +23 -8
  99. package/clients/cli/commands/blog.test.mjs +42 -1
  100. package/clients/cli/commands/build-theme.ascii-output.test.mjs +161 -0
  101. package/clients/cli/commands/build-theme.flag-docs.test.mjs +110 -0
  102. package/clients/cli/commands/build-theme.mjs +5 -5
  103. package/clients/cli/commands/build-theme.path-safety.test.mjs +86 -1
  104. package/clients/cli/commands/build-theme.variants.test.mjs +76 -0
  105. package/clients/cli/commands/build.doc.mjs +4 -1
  106. package/clients/cli/commands/build.exit-codes-doc.test.mjs +50 -0
  107. package/clients/cli/commands/build.mjs +32 -47
  108. package/clients/cli/commands/build.playbook.test.mjs +75 -0
  109. package/clients/cli/commands/build.text-fields.test.mjs +40 -0
  110. package/clients/cli/commands/component/index.mjs +2 -7
  111. package/clients/cli/commands/component-package.test.mjs +46 -0
  112. package/clients/cli/commands/component-resolution.test.mjs +21 -0
  113. package/clients/cli/commands/component.test.mjs +19 -0
  114. package/clients/cli/commands/detail-levels.test.mjs +2 -2
  115. package/clients/cli/commands/discover.broken-integration.test.mjs +48 -0
  116. package/clients/cli/commands/discover.components-flag.test.mjs +97 -0
  117. package/clients/cli/commands/discover.doc.mjs +4 -2
  118. package/clients/cli/commands/discover.mjs +3 -3
  119. package/clients/cli/commands/discover.text-projection.test.mjs +103 -0
  120. package/clients/cli/commands/doctor-integration.package-json.test.mjs +53 -0
  121. package/clients/cli/commands/doctor.mjs +6 -16
  122. package/clients/cli/commands/doctor.test.mjs +42 -0
  123. package/clients/cli/commands/gap-report.doc.mjs +16 -5
  124. package/clients/cli/commands/gap-report.test.mjs +72 -0
  125. package/clients/cli/commands/hook/index.mjs +7 -17
  126. package/clients/cli/commands/hook.text-projection.test.mjs +45 -0
  127. package/clients/cli/commands/init.doc.mjs +19 -8
  128. package/clients/cli/commands/init.flag-help.test.mjs +153 -0
  129. package/clients/cli/commands/integration-add.controls.test.mjs +132 -0
  130. package/clients/cli/commands/integration-add.doc.mjs +21 -5
  131. package/clients/cli/commands/interactive-guard.test.mjs +101 -24
  132. package/clients/cli/commands/json-contract.test.mjs +33 -0
  133. package/clients/cli/commands/layout-check.doc.mjs +14 -3
  134. package/clients/cli/commands/layout-expand.doc.mjs +21 -4
  135. package/clients/cli/commands/layout.doc.mjs +2 -2
  136. package/clients/cli/commands/layout.mjs +21 -9
  137. package/clients/cli/commands/layout.path-help.test.mjs +33 -0
  138. package/clients/cli/commands/layout.stdin-cap.test.mjs +47 -0
  139. package/clients/cli/commands/layout.text-fields.test.mjs +39 -0
  140. package/clients/cli/commands/no-prompt-wording.test.mjs +94 -0
  141. package/clients/cli/commands/search.doc.mjs +6 -3
  142. package/clients/cli/commands/search.mjs +17 -7
  143. package/clients/cli/commands/search.test.mjs +75 -0
  144. package/clients/cli/commands/swizzle.doc.mjs +2 -1
  145. package/clients/cli/commands/swizzle.path-safety.test.mjs +42 -0
  146. package/clients/cli/commands/template.doc.mjs +28 -6
  147. package/clients/cli/commands/template.flag-help.test.mjs +117 -0
  148. package/clients/cli/commands/template.path-help.test.mjs +40 -0
  149. package/clients/cli/commands/theme-add.doc.mjs +2 -1
  150. package/clients/cli/commands/theme-build.doc.mjs +7 -6
  151. package/clients/cli/commands/theme-palette-generate.test.mjs +19 -0
  152. package/clients/cli/commands/theme-template.behavior.test.mjs +12 -0
  153. package/clients/cli/commands/theme-template.doc.mjs +1 -1
  154. package/clients/cli/commands/upgrade.ascii-output.test.mjs +87 -0
  155. package/clients/cli/commands/upgrade.doc.mjs +17 -6
  156. package/clients/cli/commands/upgrade.flag-help.test.mjs +188 -0
  157. package/clients/cli/commands/upgrade.hook-output.test.mjs +88 -0
  158. package/clients/cli/index.mjs +13 -30
  159. package/clients/cli/latest-version-env.test.mjs +50 -0
  160. package/clients/cli/lib/cli-error.test.mjs +7 -0
  161. package/clients/cli/lib/component-format.mjs +9 -9
  162. package/clients/cli/lib/component-format.test.mjs +1 -1
  163. package/clients/cli/lib/define-command.mjs +32 -6
  164. package/clients/cli/lib/doc-text-ascii.test.mjs +82 -0
  165. package/clients/cli/lib/exit-codes.test.mjs +97 -0
  166. package/clients/cli/lib/hook-format.mjs +5 -5
  167. package/clients/cli/lib/json-shim.mjs +38 -2
  168. package/clients/cli/lib/json-shim.test.mjs +83 -0
  169. package/clients/cli/lib/manifest.d.ts +2 -0
  170. package/clients/cli/lib/manifest.mjs +22 -0
  171. package/clients/cli/lib/manifest.test.mjs +17 -0
  172. package/foundation/agent-docs/agent-docs.d.mts +4 -0
  173. package/foundation/agent-docs/agent-docs.mjs +69 -3
  174. package/foundation/agent-docs/agent-docs.path-safety.test.mjs +266 -4
  175. package/foundation/config/integration-debug.test.mjs +28 -3
  176. package/foundation/config/project.mjs +123 -9
  177. package/foundation/config/project.test.mjs +126 -0
  178. package/foundation/discovery/template-adapter.d.mts +14 -5
  179. package/foundation/discovery/template-adapter.fixture-refs.test.mjs +248 -0
  180. package/foundation/discovery/template-adapter.integration-isolation.test.mjs +94 -0
  181. package/foundation/discovery/template-adapter.mjs +292 -25
  182. package/foundation/discovery/theming-targets.test.mjs +4 -0
  183. package/foundation/fs/module-loader.d.mts +1 -0
  184. package/foundation/fs/module-loader.mjs +50 -1
  185. package/foundation/fs/module-loader.stdout.test.mjs +332 -0
  186. package/foundation/fs/path-safety.d.mts +3 -2
  187. package/foundation/fs/path-safety.mjs +49 -19
  188. package/foundation/fs/path-safety.test.mjs +50 -0
  189. package/foundation/fs/publish-file-hardlink-unavailable.test.mjs +129 -94
  190. package/foundation/integrations/autolink.mjs +6 -1
  191. package/foundation/response/base.d.ts +8 -4
  192. package/foundation/response/error-codes.doc.mjs +1 -2
  193. package/foundation/response/error-codes.mjs +1 -1
  194. package/foundation/response/error-codes.test.mjs +83 -0
  195. package/foundation/response/json-contract.test.mjs +11 -0
  196. package/foundation/response/json.d.mts +4 -2
  197. package/foundation/response/json.mjs +8 -10
  198. package/foundation/response/response-types.doc.mjs +10 -10
  199. package/foundation/response/response-types.doc.test.mjs +158 -0
  200. package/foundation/xle/expand.d.mts +2 -0
  201. package/foundation/xle/expand.mjs +3 -2
  202. package/foundation/xle/expand.test.mjs +54 -0
  203. package/package.json +9 -9
  204. package/clients/cli/lib/update-check.mjs +0 -83
  205. package/clients/cli/lib/update-check.test.mjs +0 -137
  206. package/clients/cli/update-hint-commands.test.mjs +0 -54
@@ -0,0 +1,88 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Subprocess test: a post-codemod hook that prints must not corrupt the
5
+ * `upgrade --json` envelope. Stdout carries exactly one envelope; the hook's
6
+ * output goes to stderr.
7
+ */
8
+
9
+ import {describe, it, expect, beforeEach, afterEach} from 'vitest';
10
+ import {spawnSync} from 'node:child_process';
11
+ import * as fs from 'node:fs';
12
+ import * as path from 'node:path';
13
+ import * as os from 'node:os';
14
+ import {fileURLToPath} from 'node:url';
15
+
16
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
17
+ const CLI = path.resolve(__dirname, '..', 'bin', 'astryx.mjs');
18
+
19
+ let tmpDir;
20
+
21
+ /** @param {string} rel @param {string} body */
22
+ function write(rel, body) {
23
+ const file = path.join(tmpDir, rel);
24
+ fs.mkdirSync(path.dirname(file), {recursive: true});
25
+ fs.writeFileSync(file, body);
26
+ }
27
+
28
+ /** @param {string[]} args */
29
+ function runCli(args) {
30
+ return spawnSync(process.execPath, [CLI, ...args], {
31
+ cwd: tmpDir,
32
+ encoding: 'utf8',
33
+ timeout: 60_000,
34
+ stdio: ['ignore', 'pipe', 'pipe'],
35
+ env: {...process.env, FORCE_COLOR: '0', CI: ''},
36
+ });
37
+ }
38
+
39
+ beforeEach(() => {
40
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-upgrade-hook-output-'));
41
+ write('package.json', JSON.stringify({name: 'consumer', private: true}));
42
+ write(
43
+ 'node_modules/@astryxdesign/core/package.json',
44
+ JSON.stringify({name: '@astryxdesign/core', version: '0.6.0'}),
45
+ );
46
+ write(
47
+ 'src/panel.tsx',
48
+ "import {useResizable} from '@astryxdesign/core';\n" +
49
+ 'export const usePanel = () => useResizable({defaultSize: 250, minSizePx: 200});\n',
50
+ );
51
+ write(
52
+ 'astryx.config.mjs',
53
+ 'export default {hooks: {postCodemod: [{name: "noisy", buildCommand: ({files}) => {\n' +
54
+ ' console.log("hook saw " + files.join(","));\n' +
55
+ ' process.stdout.write("hook raw write\\n");\n' +
56
+ ' return null;\n' +
57
+ '}}]}};\n',
58
+ );
59
+ });
60
+
61
+ afterEach(() => {
62
+ fs.rmSync(tmpDir, {recursive: true, force: true});
63
+ });
64
+
65
+ describe('upgrade post-codemod hook output', () => {
66
+ it('keeps --json stdout to one envelope and sends hook output to stderr', () => {
67
+ const r = runCli([
68
+ '--json',
69
+ 'upgrade',
70
+ '--from',
71
+ '0.5.0',
72
+ '--codemod',
73
+ 'rename-resizable-pixel-bounds',
74
+ '--apply',
75
+ ]);
76
+
77
+ expect(r.signal).toBeNull();
78
+ expect(r.status).toBe(0);
79
+ const envelope = JSON.parse(r.stdout);
80
+ expect(envelope.type).toBe('upgrade.run');
81
+ expect(envelope.data.filesChanged).toBe(1);
82
+ expect(r.stderr).toContain('hook saw src/panel.tsx');
83
+ expect(r.stderr).toContain('hook raw write');
84
+ expect(fs.readFileSync(path.join(tmpDir, 'src/panel.tsx'), 'utf8')).toContain(
85
+ 'minSize: 200',
86
+ );
87
+ });
88
+ });
@@ -16,7 +16,6 @@ import {Command, Option} from 'commander';
16
16
  import {fileURLToPath} from 'node:url';
17
17
  import * as fs from 'node:fs';
18
18
  import * as path from 'node:path';
19
- import {checkForUpdate} from './lib/update-check.mjs';
20
19
  import {getCliInvocation} from '../../foundation/env/package-manager.mjs';
21
20
  import {API_VERSION, setJsonMode} from '../../foundation/response/json.mjs';
22
21
  import {buildManifest} from './lib/manifest.mjs';
@@ -25,7 +24,8 @@ import {emit, section, text, records} from './formatters/index.mjs';
25
24
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
26
25
  import {levenshteinDistance} from '../../foundation/text/string-utils.mjs';
27
26
  import {installJsonShim} from './lib/json-shim.mjs';
28
- import {markReportsResult} from './lib/define-command.mjs';
27
+ import {addExitCodesHelp, markReportsResult} from './lib/define-command.mjs';
28
+ import {doc as manifestDoc} from './commands/manifest.doc.mjs';
29
29
  import {isAstryxInitialized} from '../../foundation/agent-docs/agent-docs.mjs';
30
30
  import * as debug from '../../foundation/debug/index.mjs';
31
31
 
@@ -275,7 +275,6 @@ const commands = [
275
275
  {name: 'doctor', path: './commands/doctor.mjs', register: 'registerDoctor'},
276
276
  ];
277
277
 
278
- const UPDATE_HINT_COMMANDS = new Set(['component', 'docs']);
279
278
  const SETUP_NUDGE_EXEMPT = new Set(['init', 'agent-docs']);
280
279
 
281
280
  /**
@@ -352,7 +351,7 @@ export async function createProgram() {
352
351
  )
353
352
  .option(
354
353
  '--json',
355
- 'Output as typed JSON. Success envelope: { type, data }. Error envelope: { error, suggestions? }.',
354
+ 'Output as typed JSON. Success envelope: { apiVersion, type, data, meta? }. Error envelope: { apiVersion, error, code, suggestions? }.',
356
355
  )
357
356
  .addHelpCommand('help', 'Show all commands')
358
357
  .action((options, cmd) => {
@@ -499,25 +498,6 @@ export async function createProgram() {
499
498
  process.exit(1);
500
499
  });
501
500
 
502
- /**
503
- * Post-action hook: print update hint after any command output.
504
- * Only fires for commands that produce output agents read (component, docs, etc.).
505
- * Suppressed when --json is active to avoid contaminating stdout.
506
- */
507
- program.hook('postAction', (thisCommand, actionCommand) => {
508
- if (program.opts().json) return;
509
- try {
510
- if (UPDATE_HINT_COMMANDS.has(actionCommand.name())) {
511
- const hint = checkForUpdate();
512
- if (hint) {
513
- console.error(`\n${hint}`);
514
- }
515
- }
516
- } catch {
517
- // Never let update check break the CLI
518
- }
519
- });
520
-
521
501
  /**
522
502
  * Enforcement layer 3 — setup nudge. If this project hasn't run `astryx init`
523
503
  * yet (no Astryx marker in any agent-doc file — see isAstryxInitialized), remind
@@ -557,16 +537,18 @@ export async function createProgram() {
557
537
  mod[cmd.register](program);
558
538
  } catch (e) {
559
539
  // Command fails to load but CLI still works
540
+ const reason = /** @type {any} */ (e).message;
560
541
  const stub = program
561
542
  .command(cmd.name)
562
- .description(`(failed to load: ${/** @type {any} */ (e).message})`)
543
+ .description(`(failed to load: ${reason})`)
563
544
  .action(() => {
564
545
  // Nothing loaded, so nothing was answered — say that rather than
565
546
  // leaving the run's result unreported.
566
547
  debug.recordCommandResult(debug.NO_RESULT_SET);
567
- console.error(`Command "${cmd.name}" failed to load:`);
568
- console.error(/** @type {any} */ (e).message);
569
- process.exit(1);
548
+ // cliError, so --json still gets its one envelope.
549
+ cliError(`Command "${cmd.name}" failed to load: ${reason}`, {
550
+ code: ERROR_CODES.ERR_UNKNOWN,
551
+ });
570
552
  });
571
553
  markReportsResult(stub);
572
554
  }
@@ -601,20 +583,21 @@ export async function createProgram() {
601
583
  }
602
584
  // Human-readable summary as greppable records (agents should use --json).
603
585
  // One record per command: name, whether it supports --json, and the
604
- // description.
586
+ // description. Field names are the manifest entry's own keys.
605
587
  emit(
606
588
  section(`${manifest.name} v${manifest.version} (${manifest.commands.length} commands)`),
607
589
  records(
608
590
  manifest.commands.map(c => ({
609
- command: c.name,
591
+ name: c.name,
610
592
  json: c.json ? 'yes' : '',
611
593
  description: c.description || '',
612
594
  })),
613
- {fields: ['command', 'json', 'description']},
595
+ {fields: ['name', 'json', 'description']},
614
596
  ),
615
597
  text(`Run \`${getCliInvocation()} manifest --json\` for the full structured manifest.`),
616
598
  );
617
599
  });
600
+ addExitCodesHelp(manifestCommand, manifestDoc.exitCodes);
618
601
  markReportsResult(manifestCommand);
619
602
 
620
603
  // Hidden command used by package.json postinstall scripts
@@ -0,0 +1,50 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file ASTRYX_LATEST_VERSION is not a CLI control: setting it changes nothing
5
+ * a command prints. It used to append an update hint to `component` and
6
+ * `docs`.
7
+ */
8
+
9
+ import {describe, it, expect, beforeEach, afterEach} 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
+
15
+ const VARIABLE = 'ASTRYX_LATEST_VERSION';
16
+
17
+ /** @type {string} */
18
+ let dir;
19
+ /** @type {string | undefined} */
20
+ let saved;
21
+
22
+ beforeEach(() => {
23
+ saved = process.env[VARIABLE];
24
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-latest-version-'));
25
+ // A project on an old core, so a "newer version" hint would have a reason to fire.
26
+ fs.writeFileSync(
27
+ path.join(dir, 'package.json'),
28
+ JSON.stringify({name: 'app', private: true, dependencies: {'@astryxdesign/core': '^0.0.1'}}),
29
+ );
30
+ });
31
+
32
+ afterEach(() => {
33
+ if (saved === undefined) delete process.env[VARIABLE];
34
+ else process.env[VARIABLE] = saved;
35
+ fs.rmSync(dir, {recursive: true, force: true});
36
+ });
37
+
38
+ describe('ASTRYX_LATEST_VERSION', () => {
39
+ it('does not change what astryx docs prints', async () => {
40
+ delete process.env[VARIABLE];
41
+ const without = await runCli(['docs'], {cwd: dir});
42
+ process.env[VARIABLE] = '999.0.0';
43
+ const withVariable = await runCli(['docs'], {cwd: dir});
44
+
45
+ expect(withVariable.status).toBe(without.status);
46
+ expect(withVariable.stdout).toBe(without.stdout);
47
+ expect(withVariable.stderr).toBe(without.stderr);
48
+ expect(withVariable.stderr).not.toMatch(/newer version/i);
49
+ });
50
+ });
@@ -133,6 +133,13 @@ describe('cliError — JSON mode', () => {
133
133
  expect(env.suggestions).toEqual([{name: 'Button', reason: 'closest match'}]);
134
134
  });
135
135
 
136
+ it('replaces an unregistered code with ERR_UNKNOWN', () => {
137
+ expect(() =>
138
+ cliError('EACCES: permission denied', {code: 'EACCES'}),
139
+ ).toThrow('__exit_1__');
140
+ expect(JSON.parse(stdout[0]).code).toBe('ERR_UNKNOWN');
141
+ });
142
+
136
143
  it('always exits 1 in JSON mode (custom exitCode is ignored — contract)', () => {
137
144
  expect(() => cliError('msg', {exitCode: 2})).toThrow('__exit_1__');
138
145
  expect(exitCode).toBe(1);
@@ -71,7 +71,7 @@ function formatPropsTable(props) {
71
71
  lines.push('| Prop | Type | Default | Description |');
72
72
  lines.push('|------|------|---------|-------------|');
73
73
  for (const p of props) {
74
- const def = p.default ? `\`${mdCell(p.default)}\`` : '—';
74
+ const def = p.default ? `\`${mdCell(p.default)}\`` : '-';
75
75
  const req = p.required ? ' **(required)**' : '';
76
76
  lines.push(
77
77
  `| \`${mdCell(p.name)}\` | \`${mdCell(p.type)}\` | ${def} | ${mdCell(p.description)}${req} |`,
@@ -190,11 +190,11 @@ function formatTargetsTable(docs, themeData) {
190
190
  ...themeVariants.map((/** @type {string} */ v) => `${v}*`),
191
191
  ];
192
192
 
193
- const variantsStr = variantParts.length > 0 ? variantParts.join(', ') : '—';
194
- const statesStr = states.length > 0 ? states.join(', ') : '—';
193
+ const variantsStr = variantParts.length > 0 ? variantParts.join(', ') : '-';
194
+ const statesStr = states.length > 0 ? states.join(', ') : '-';
195
195
  const dataAttrs = getTargetDataAttributes(target);
196
196
  const dataAttrsStr =
197
- dataAttrs.length > 0 ? dataAttrs.map(attr => `\`${attr}\``).join(', ') : '—';
197
+ dataAttrs.length > 0 ? dataAttrs.map(attr => `\`${attr}\``).join(', ') : '-';
198
198
 
199
199
  const className = target.deprecatedFor
200
200
  ? `\`${target.className}\` _(deprecated; use \`${target.deprecatedFor}\`)_`
@@ -342,7 +342,7 @@ export function formatFull(docs, options = {}) {
342
342
  const publicVars = docs.theming.vars.filter((/** @type {any} */ v) => !v.private && !v.derived);
343
343
 
344
344
  if (publicVars.length > 0) {
345
- sections.push('**Themeable CSS variables** — additional properties that can be overridden in `defineTheme` component overrides.\n');
345
+ sections.push('**Themeable CSS variables** - additional properties that can be overridden in `defineTheme` component overrides.\n');
346
346
  const varLines = [];
347
347
  varLines.push('| CSS Variable | Default | Description |');
348
348
  varLines.push('|-------------|---------|-------------|');
@@ -544,7 +544,7 @@ export function formatBrief(docs, componentName, importHint, options = {}) {
544
544
  signatureProps.length > 0
545
545
  ? `${displayName}(${signatureProps.join(', ')})`
546
546
  : displayName;
547
- output.push(importHint ? `${sigStr} ← from '${importHint}'` : sigStr);
547
+ output.push(importHint ? `${sigStr} <- from '${importHint}'` : sigStr);
548
548
 
549
549
  // Description (shortened)
550
550
  if (description) {
@@ -569,7 +569,7 @@ export function formatBrief(docs, componentName, importHint, options = {}) {
569
569
  // Derived properties (if any)
570
570
  if (docs.theming?.derived?.length) {
571
571
  const derivedNames = docs.theming.derived
572
- .map((/** @type {any} */ d) => d.expand === 'container' ? `${d.property} → container tokens` : `${d.property} → ${(d.vars || []).join(', ')}`)
572
+ .map((/** @type {any} */ d) => d.expand === 'container' ? `${d.property} -> container tokens` : `${d.property} -> ${(d.vars || []).join(', ')}`)
573
573
  .join('; ');
574
574
  output.push(` Derived: ${derivedNames}`);
575
575
  }
@@ -579,7 +579,7 @@ export function formatBrief(docs, componentName, importHint, options = {}) {
579
579
  const { themeData = null } = options;
580
580
  const targetParts = docs.theming.targets.map((/** @type {any} */ t) => {
581
581
  const parts = [t.className];
582
- if (t.deprecatedFor) parts.push(`deprecated→${t.deprecatedFor}`);
582
+ if (t.deprecatedFor) parts.push(`deprecated->${t.deprecatedFor}`);
583
583
  const dataAttrs = getTargetDataAttributes(t);
584
584
  if (dataAttrs.length) parts.push(`preferred attrs: ${dataAttrs.join(', ')}`);
585
585
  if (t.visualProps?.length) parts.push(`variants: ${t.visualProps.join(', ')}`);
@@ -595,7 +595,7 @@ export function formatBrief(docs, componentName, importHint, options = {}) {
595
595
 
596
596
  // Other props
597
597
  if (otherProps.length > 0) {
598
- output.push(` ${otherProps.join(' · ')}`);
598
+ output.push(` ${otherProps.join(', ')}`);
599
599
  }
600
600
 
601
601
  // First code example
@@ -157,7 +157,7 @@ describe('deprecated theming target guidance', () => {
157
157
 
158
158
  it('keeps the replacement in brief agent guidance', () => {
159
159
  expect(formatBrief(docs, 'Example')).toContain(
160
- 'astryx-old-target deprecated→new-target',
160
+ 'astryx-old-target deprecated->new-target',
161
161
  );
162
162
  });
163
163
  });
@@ -25,6 +25,7 @@
25
25
  */
26
26
 
27
27
  import {recordCommandResult} from '../../../foundation/debug/index.mjs';
28
+ import {text} from '../formatters/index.mjs';
28
29
 
29
30
  /**
30
31
  * Marks a Commander command that reports what it answered with, and says HOW:
@@ -78,6 +79,21 @@ export function markReportsResult(cmd) {
78
79
  return cmd;
79
80
  }
80
81
 
82
+ /** The CommandDoc and wrapped FunctionDoc a command was built from. */
83
+ export const COMMAND_DOCS = Symbol.for('astryx.command.docs');
84
+
85
+ /**
86
+ * The docs a command was built from; undefined for a hand-registered command.
87
+ * @param {import('commander').Command} cmd
88
+ * @returns {{
89
+ * doc: import('@astryxdesign/cli/authoring').CommandDoc,
90
+ * fn?: import('@astryxdesign/cli/authoring').FunctionDoc,
91
+ * } | undefined}
92
+ */
93
+ export function commandDocsOf(cmd) {
94
+ return /** @type {any} */ (cmd)?.[COMMAND_DOCS];
95
+ }
96
+
81
97
  /**
82
98
  * Build a Commander command from a CommandDoc and attach it to `parent`.
83
99
  *
@@ -102,6 +118,7 @@ export function defineCommand(parent, doc, {fn, action} = {}) {
102
118
  .join(' ');
103
119
 
104
120
  const cmd = parent.command(argSpec ? `${token} ${argSpec}` : token);
121
+ Object.defineProperty(cmd, COMMAND_DOCS, {value: {doc, fn}, configurable: true});
105
122
  if (doc.summary) cmd.description(doc.summary);
106
123
 
107
124
  const paramDesc = (/** @type {string | undefined} */ name) =>
@@ -126,12 +143,10 @@ export function defineCommand(parent, doc, {fn, action} = {}) {
126
143
  cmd.addOption(option);
127
144
  }
128
145
 
129
- // `choices` and `examples` are doc metadata surfaced by `astryx docs` and the
130
- // doc site; they are intentionally NOT injected into `--help` here. Choices
131
- // stay described in the option text (Commander `.choices()` would also change
132
- // validation from the api layer's ERR_INVALID_ARGUMENT), and the current CLI
133
- // help carries no per-command examples epilog. Keeping both out preserves the
134
- // exact `--help`/manifest surface as registrations migrate to this converter.
146
+ // Help ends with the documented exit codes. `choices` stay in the option
147
+ // text: Commander `.choices()` would replace the api layer's
148
+ // ERR_INVALID_ARGUMENT validation.
149
+ addExitCodesHelp(cmd, doc.exitCodes);
135
150
 
136
151
  if (action) {
137
152
  // The recording seam. An action's job ends at "here is what I answered
@@ -149,3 +164,14 @@ export function defineCommand(parent, doc, {fn, action} = {}) {
149
164
  }
150
165
  return cmd;
151
166
  }
167
+
168
+ /**
169
+ * End `cmd`'s help with a CommandDoc's exit codes.
170
+ * @param {import('commander').Command} cmd
171
+ * @param {import('@astryxdesign/cli/authoring').CommandDoc['exitCodes']} exitCodes
172
+ */
173
+ export function addExitCodesHelp(cmd, exitCodes) {
174
+ if (!exitCodes?.length) return;
175
+ const lines = exitCodes.map(({code, when}) => ` ${code} ${when}`);
176
+ cmd.addHelpText('after', `\n${text(['Exit codes:', ...lines].join('\n')).toString()}`);
177
+ }
@@ -0,0 +1,82 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file The component and hook text renderers add no non-ASCII characters of
5
+ * their own: given ASCII-only docs, every view they produce is plain ASCII.
6
+ */
7
+
8
+ import {describe, it, expect} from 'vitest';
9
+ import {
10
+ formatBrief,
11
+ formatCompact,
12
+ formatFull,
13
+ formatProps,
14
+ } from './component-format.mjs';
15
+ import {
16
+ formatHookBrief,
17
+ formatHookCompact,
18
+ formatHookFull,
19
+ formatHookParams,
20
+ } from './hook-format.mjs';
21
+
22
+ const NON_ASCII = /[\u0080-\uffff]/g;
23
+
24
+ /** @param {string} out @returns {string[]} */
25
+ const nonAscii = out => out.match(NON_ASCII) ?? [];
26
+
27
+ // Every optional field left empty and every optional path taken, so each
28
+ // placeholder, separator, and arrow the renderers emit shows up at least once.
29
+ const componentDoc = {
30
+ name: 'Widget',
31
+ description: 'A widget for tests.',
32
+ props: [
33
+ {name: 'variant', type: "'solid' | 'ghost'", description: 'Look.'},
34
+ {name: 'label', type: 'string', description: 'Label.', required: true},
35
+ {name: 'disabled', type: 'boolean', description: 'Disables it.'},
36
+ {name: 'tone', type: 'string', description: 'Tone.'},
37
+ ],
38
+ theming: {
39
+ vars: [{name: '--widget-gap', default: '8px', description: 'Gap.'}],
40
+ derived: [
41
+ {property: 'padding', expand: 'container'},
42
+ {property: 'radius', vars: ['--widget-radius']},
43
+ ],
44
+ targets: [
45
+ {className: 'astryx-widget', deprecatedFor: 'astryx-widget-v2'},
46
+ {className: 'astryx-widget-v2', visualProps: ['variant']},
47
+ ],
48
+ },
49
+ };
50
+
51
+ const hookDoc = {
52
+ name: 'useWidget',
53
+ importPath: '@astryxdesign/core/useWidget',
54
+ usage: {description: 'Widget behavior.'},
55
+ params: [
56
+ {name: 'options', type: 'object', description: 'Options.', required: true},
57
+ {name: 'delay', type: 'number', description: 'Delay.'},
58
+ ],
59
+ returns: [{name: 'open', type: 'boolean', description: 'Open state.'}],
60
+ };
61
+
62
+ describe('component text output is ASCII', () => {
63
+ it.each([
64
+ ['formatFull', () => formatFull(componentDoc)],
65
+ ['formatCompact', () => formatCompact(componentDoc, 'Widget')],
66
+ ['formatBrief', () => formatBrief(componentDoc, 'Widget', '@astryxdesign/core/Widget')],
67
+ ['formatProps', () => formatProps(componentDoc, 'Widget')],
68
+ ])('%s', (_name, render) => {
69
+ expect(nonAscii(render())).toEqual([]);
70
+ });
71
+ });
72
+
73
+ describe('hook text output is ASCII', () => {
74
+ it.each([
75
+ ['formatHookFull', () => formatHookFull(hookDoc)],
76
+ ['formatHookCompact', () => formatHookCompact(hookDoc, hookDoc.importPath)],
77
+ ['formatHookBrief', () => formatHookBrief(hookDoc)],
78
+ ['formatHookParams', () => formatHookParams(hookDoc)],
79
+ ])('%s', (_name, render) => {
80
+ expect(nonAscii(render())).toEqual([]);
81
+ });
82
+ });
@@ -0,0 +1,97 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Every CommandDoc's exit codes reach generated help and the manifest.
5
+ */
6
+
7
+ import * as fs from 'node:fs';
8
+ import * as os from 'node:os';
9
+ import * as path from 'node:path';
10
+ import {fileURLToPath, pathToFileURL} from 'node:url';
11
+ import {describe, it, expect} from 'vitest';
12
+ import {program, JSON_SUPPORTED} from '../index.mjs';
13
+ import {buildManifest} from './manifest.mjs';
14
+ import {runCli} from '../../../test-utils/run-cli.mjs';
15
+
16
+ const COMMANDS = path.join(path.dirname(fileURLToPath(import.meta.url)), '../commands');
17
+
18
+ /** @type {any[]} */
19
+ const commandDocs = [];
20
+ for (const file of fs.readdirSync(COMMANDS).sort()) {
21
+ if (!file.endsWith('.doc.mjs')) continue;
22
+ const {doc} = await import(pathToFileURL(path.join(COMMANDS, file)).href);
23
+ if (doc?.type === 'command') commandDocs.push(doc);
24
+ }
25
+
26
+ const manifest = buildManifest(program, {jsonSupported: JSON_SUPPORTED, version: '0.0.0-test'});
27
+ /** @type {Map<string, any>} */
28
+ const entries = new Map();
29
+ const walk = (/** @type {any} */ c) => {
30
+ entries.set(c.name, c);
31
+ (c.subcommands || []).forEach(walk);
32
+ };
33
+ manifest.commands.forEach(walk);
34
+
35
+ describe('command exit codes', () => {
36
+ it('every CommandDoc documents its exit codes', () => {
37
+ expect(commandDocs.length).toBeGreaterThan(30);
38
+ for (const doc of commandDocs) {
39
+ expect(doc.exitCodes?.length, doc.name).toBeGreaterThan(0);
40
+ }
41
+ });
42
+
43
+ it.each(commandDocs.map((d) => [d.name, d]))(
44
+ '`astryx %s --help` lists the documented exit codes',
45
+ async (name, doc) => {
46
+ const {status, stdout} = await runCli([...name.split(' '), '--help']);
47
+ expect(status).toBe(0);
48
+ const section = stdout.slice(stdout.indexOf('\nExit codes:\n'));
49
+ expect(section.startsWith('\nExit codes:\n'), stdout).toBe(true);
50
+ expect(stdout.match(/\nExit codes?:\n/g), 'one exit-code section').toHaveLength(1);
51
+ for (const {code, when} of doc.exitCodes) {
52
+ expect(section).toContain(`\n ${code} ${when}\n`);
53
+ }
54
+ },
55
+ );
56
+
57
+ it('bare `astryx layout` exits 1 in both modes, as documented', async () => {
58
+ const doc = commandDocs.find((d) => d.name === 'layout');
59
+ expect(doc.exitCodes.find((e) => e.code === 1)?.when).toMatch(/^no subcommand/);
60
+ expect((await runCli(['layout'])).status).toBe(1);
61
+ expect((await runCli(['layout', '--json'])).status).toBe(1);
62
+ });
63
+
64
+ it('`astryx discover` with a blank query exits 1 only when packages are discovered', async () => {
65
+ const doc = commandDocs.find((d) => d.name === 'discover');
66
+ expect(doc.exitCodes.find((e) => e.code === 1)?.when).toMatch(/blank query when packages are discovered/);
67
+ const project = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-exit-discover-'));
68
+ try {
69
+ expect((await runCli(['discover', ' ', '--json'], {cwd: project})).status).toBe(0);
70
+ const pkg = path.join(project, 'node_modules/@acme/ui');
71
+ fs.mkdirSync(path.join(pkg, 'components'), {recursive: true});
72
+ fs.writeFileSync(path.join(pkg, 'package.json'), '{"name":"@acme/ui","version":"1.0.0","type":"module"}');
73
+ fs.writeFileSync(path.join(pkg, 'astryx.integration.mjs'), "export default {components: './components'};\n");
74
+ fs.writeFileSync(
75
+ path.join(pkg, 'components/Widget.doc.mjs'),
76
+ 'export const doc = {type: "component", name: "Widget", description: "A widget"};\n',
77
+ );
78
+ fs.writeFileSync(path.join(pkg, 'components/Widget.tsx'), 'export function Widget() { return null; }\n');
79
+ fs.writeFileSync(path.join(project, 'package.json'), '{"name":"app","type":"module"}');
80
+ fs.writeFileSync(path.join(project, 'astryx.config.mjs'), "export default {integrations: ['@acme/ui']};\n");
81
+ expect((await runCli(['discover', '--json'], {cwd: project})).status).toBe(0);
82
+ const blank = await runCli(['discover', ' ', '--json'], {cwd: project});
83
+ expect(blank.status).toBe(1);
84
+ expect(JSON.parse(blank.stdout).code).toBe('ERR_INVALID_ARGUMENT');
85
+ } finally {
86
+ fs.rmSync(project, {recursive: true, force: true});
87
+ }
88
+ });
89
+
90
+ it('the manifest carries every command exit code', () => {
91
+ for (const doc of commandDocs) {
92
+ expect(entries.get(doc.name)?.exitCodes, doc.name).toEqual(
93
+ doc.exitCodes.map(({code, when}) => ({code, when})),
94
+ );
95
+ }
96
+ });
97
+ });
@@ -57,7 +57,7 @@ function formatParamsTable(params) {
57
57
  lines.push('| Param | Type | Default | Description |');
58
58
  lines.push('|-------|------|---------|-------------|');
59
59
  for (const p of params) {
60
- const def = p.default ? `\`${mdCell(p.default)}\`` : '\u2014';
60
+ const def = p.default ? `\`${mdCell(p.default)}\`` : '-';
61
61
  const req = p.required ? ' **(required)**' : '';
62
62
  lines.push(
63
63
  `| \`${mdCell(p.name)}\` | \`${mdCell(p.type)}\` | ${def} | ${mdCell(p.description)}${req} |`,
@@ -198,7 +198,7 @@ export function formatHookCompact(docs, importPath) {
198
198
  /**
199
199
  * Format a brief, LLM-optimized hook summary.
200
200
  * Matches component formatBrief conventions:
201
- * signature ← from 'import/path'
201
+ * signature <- from 'import/path'
202
202
  * description
203
203
  * key params
204
204
  * @param {any} docs
@@ -211,7 +211,7 @@ export function formatHookBrief(docs) {
211
211
  // Signature line with import hint (matches component brief)
212
212
  const sig = buildSignature(docs);
213
213
  const imp = docs.importPath;
214
- output.push(imp ? `${sig} \u2190 from '${imp}'` : sig);
214
+ output.push(imp ? `${sig} <- from '${imp}'` : sig);
215
215
 
216
216
  // Description (shortened, matches component brief)
217
217
  const desc = docs.usage?.description || '';
@@ -225,12 +225,12 @@ export function formatHookBrief(docs) {
225
225
  output.push(` Related: ${docs.relatedComponents.join(', ')}`);
226
226
  }
227
227
 
228
- // Key params (matches component brief 'prop · prop' line)
228
+ // Key params (matches component brief 'prop, prop' line)
229
229
  const paramNames = (docs.params || [])
230
230
  .filter((/** @type {any} */ p) => !p.name.includes('.'))
231
231
  .map((/** @type {any} */ p) => p.required ? `${p.name}: ${p.type.split('|')[0].trim()}` : p.name);
232
232
  if (paramNames.length > 0) {
233
- output.push(` ${paramNames.join(' \u00b7 ')}`);
233
+ output.push(` ${paramNames.join(', ')}`);
234
234
  }
235
235
 
236
236
  return output.join('\n') + '\n';