@astryxdesign/cli 0.7.14-canary.gfdb9213 → 0.7.14

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 (95) hide show
  1. package/CHANGELOG.md +197 -0
  2. package/api/theme/_adapter.d.mts +33 -0
  3. package/api/theme/_adapter.mjs +352 -16
  4. package/api/theme/build/build.mjs +261 -10
  5. package/api/theme/eject/eject.mjs +13 -1
  6. package/api/theme/list/list.mjs +11 -2
  7. package/api/theme/template/template.mjs +139 -6
  8. package/api/theme/theme.type.d.mts +15 -1
  9. package/api/theme/theme.type.mjs +9 -3
  10. package/api/theme/themeAdd.doc.mjs +1 -1
  11. package/api/theme/themeBuild.doc.mjs +10 -2
  12. package/api/theme/themeEject.doc.mjs +2 -2
  13. package/api/theme/themeListAvailable.doc.mjs +1 -1
  14. package/api/theme/themeRemove.doc.mjs +1 -1
  15. package/api/theme/themeTemplate.doc.mjs +8 -0
  16. package/api/theme/themeUse.doc.mjs +1 -1
  17. package/api/theme-edit/_adapter.d.mts +10 -2
  18. package/api/theme-edit/_adapter.mjs +52 -31
  19. package/api/theme-edit/_check.d.mts +28 -25
  20. package/api/theme-edit/_check.mjs +586 -548
  21. package/api/theme-edit/_color.d.mts +28 -2
  22. package/api/theme-edit/_color.mjs +306 -68
  23. package/api/theme-edit/_compiler.d.mts +8 -4
  24. package/api/theme-edit/_compiler.mjs +30 -27
  25. package/api/theme-edit/_context.d.mts +10 -4
  26. package/api/theme-edit/_context.mjs +21 -4
  27. package/api/theme-edit/_edit.mjs +300 -43
  28. package/api/theme-edit/_how-commands.d.mts +91 -0
  29. package/api/theme-edit/_how-commands.mjs +269 -0
  30. package/api/theme-edit/_how-question.d.mts +57 -0
  31. package/api/theme-edit/_how-question.mjs +2574 -0
  32. package/api/theme-edit/_how.d.mts +25 -17
  33. package/api/theme-edit/_how.mjs +727 -305
  34. package/api/theme-edit/_palette.d.mts +127 -19
  35. package/api/theme-edit/_palette.mjs +1313 -399
  36. package/api/theme-edit/_parts.mjs +36 -3
  37. package/api/theme-edit/_png.d.mts +18 -6
  38. package/api/theme-edit/_png.mjs +135 -25
  39. package/api/theme-edit/_preview-app.d.mts +26 -7
  40. package/api/theme-edit/_preview-app.mjs +1611 -280
  41. package/api/theme-edit/_preview.d.mts +4 -2
  42. package/api/theme-edit/_preview.mjs +18 -7
  43. package/api/theme-edit/_settings.d.mts +56 -5
  44. package/api/theme-edit/_settings.mjs +197 -49
  45. package/api/theme-edit/_tables.d.mts +0 -12
  46. package/api/theme-edit/_tables.mjs +24 -97
  47. package/api/theme-edit/theme-edit.type.d.mts +22 -5
  48. package/api/theme-edit/theme-edit.type.mjs +17 -6
  49. package/api/theme-edit/themeEditHow.doc.mjs +13 -3
  50. package/api/theme-edit/themeEditNew.doc.mjs +2 -1
  51. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +16 -4
  52. package/api/theme-edit/themeEditPreviewApp.doc.mjs +12 -4
  53. package/api/theme-edit/themeEditPreviewList.doc.mjs +9 -1
  54. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +27 -2
  55. package/api/theme-edit/themeEditUndo.doc.mjs +1 -1
  56. package/assets/docs.generated.json +1 -0
  57. package/assets/preview-app/gitignore +3 -0
  58. package/assets/templates/components.generated.json +1 -0
  59. package/clients/cli/bin/astryx.mjs +37 -5
  60. package/clients/cli/commands/experimental/theme.mjs +231 -31
  61. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +14 -5
  62. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +0 -1
  63. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +1 -1
  64. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +3 -2
  65. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +2 -2
  66. package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +2 -2
  67. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +2 -2
  68. package/clients/cli/commands/experimental-theme-targets.doc.mjs +1 -1
  69. package/clients/cli/commands/experimental-theme.doc.mjs +2 -2
  70. package/clients/cli/commands/theme-build.doc.mjs +1 -1
  71. package/clients/cli/commands/theme-eject.doc.mjs +3 -3
  72. package/clients/cli/commands/theme-remove.doc.mjs +2 -2
  73. package/clients/cli/commands/theme-template.doc.mjs +11 -4
  74. package/clients/cli/commands/theme.mjs +104 -40
  75. package/clients/cli/commands.generated.json +1 -0
  76. package/clients/cli/index.mjs +96 -4
  77. package/clients/cli/lib/json-shim.mjs +29 -1
  78. package/foundation/config/project.d.mts +16 -2
  79. package/foundation/config/project.mjs +40 -6
  80. package/foundation/config/theme-state.d.mts +9 -0
  81. package/foundation/config/theme-state.mjs +20 -1
  82. package/foundation/discovery/template-adapter.d.mts +12 -1
  83. package/foundation/discovery/template-adapter.mjs +24 -1
  84. package/foundation/discovery/template-needs.d.mts +7 -0
  85. package/foundation/discovery/template-needs.mjs +117 -8
  86. package/foundation/discovery/template-source-tree.d.mts +5 -1
  87. package/foundation/discovery/template-source-tree.mjs +6 -4
  88. package/foundation/discovery/theme-discovery.d.mts +14 -3
  89. package/foundation/discovery/theme-discovery.mjs +45 -12
  90. package/foundation/doc-compiler/import.mjs +68 -3
  91. package/foundation/doc-compiler/stored-docs.d.mts +27 -0
  92. package/foundation/doc-compiler/stored-docs.mjs +65 -0
  93. package/foundation/fs/fs-error.d.mts +17 -0
  94. package/foundation/fs/fs-error.mjs +34 -0
  95. package/package.json +6 -6
@@ -12,7 +12,7 @@
12
12
  * the full program in program.mjs.
13
13
  */
14
14
 
15
- import {Command, Option} from 'commander';
15
+ import {Command, Help, 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';
@@ -363,8 +363,10 @@ const READS_EVERY_COMMAND = new Set(['manifest']);
363
363
  * first operand after the root's own options, so this reads the arguments the
364
364
  * same way. It returns that one command, no command for a run that only
365
365
  * prints the version, or null for every command. These runs load every
366
- * command: help, the manifest, `help <command>`, an unknown word, and a flag
367
- * the root does not declare. They print or read the whole list.
366
+ * command: the root help when no stored list ships (a checkout; the published
367
+ * package prints it from the list, see `printsRootHelp`), the manifest,
368
+ * `help <command>`, an unknown word, and a flag the root does not declare.
369
+ * They print or read the whole list.
368
370
  *
369
371
  * @param {import('commander').Command} program the root, with its options
370
372
  * @param {string[]} argv the arguments after `astryx`
@@ -398,6 +400,93 @@ export function commandsForArgs(program, argv) {
398
400
  return printsVersion ? new Set() : null;
399
401
  }
400
402
 
403
+ /**
404
+ * Make `help <group> <command> ...` print the help of the deepest command the
405
+ * words name. Commander's help command reads only the first word, so
406
+ * `help theme build` printed the help of `theme`. Commander has no public hook
407
+ * for this; the override wraps its help dispatch and falls back to it.
408
+ * @param {import('commander').Command} program
409
+ */
410
+ export function resolveDeepHelp(program) {
411
+ const root = /** @type {any} */ (program);
412
+ // A Commander release without this method keeps its own help dispatch.
413
+ if (typeof root._dispatchHelpCommand !== 'function') return;
414
+ const dispatch = root._dispatchHelpCommand.bind(root);
415
+ root._dispatchHelpCommand = (/** @type {string | undefined} */ name) => {
416
+ const words = (root.args ?? [])
417
+ .slice(1)
418
+ .filter((/** @type {string} */ word) => !word.startsWith('-'));
419
+ /** @type {any} */
420
+ let target = root;
421
+ for (const word of words) {
422
+ const next = target._findCommand(word);
423
+ if (!next) break;
424
+ target = next;
425
+ }
426
+ if (words.length > 1 && target !== root && !target._executableHandler) {
427
+ target.help();
428
+ }
429
+ return dispatch(name);
430
+ };
431
+ }
432
+
433
+ /**
434
+ * Where the root help's command list is stored: each command's name, and the
435
+ * term and description the root help prints for it, as the fully loaded
436
+ * program gives them. `prepack` writes it (scripts/generate-command-list.mjs),
437
+ * so the published package prints its root help without loading every
438
+ * command. A checkout has none and loads them.
439
+ */
440
+ export const COMMAND_LIST_FILE = path.join(__dirname, 'commands.generated.json');
441
+
442
+ /**
443
+ * Whether a run only prints the root help: `--help`, `-h` or `help`, alone.
444
+ * @param {string[]} argv
445
+ * @returns {boolean}
446
+ */
447
+ function printsRootHelp(argv) {
448
+ return argv.length === 1 && ['--help', '-h', 'help'].includes(argv[0]);
449
+ }
450
+
451
+ /**
452
+ * The stored command list, or null when there is none or it cannot be read.
453
+ * @returns {Array<{name: string, term: string, description: string}> | null}
454
+ */
455
+ function storedCommandList() {
456
+ try {
457
+ return JSON.parse(fs.readFileSync(COMMAND_LIST_FILE, 'utf-8'));
458
+ } catch {
459
+ return null;
460
+ }
461
+ }
462
+
463
+ /**
464
+ * Give `program` a command for each stored row, which the root help prints
465
+ * with the row's term and description. Commander adds its own `help`
466
+ * command, so a stored `help` row adds none.
467
+ * @param {import('commander').Command} program
468
+ * @param {Array<{name: string, term: string, description: string}>} rows
469
+ */
470
+ function listStoredCommands(program, rows) {
471
+ /** @type {Map<string, {term: string, description: string}>} */
472
+ const byName = new Map();
473
+ for (const row of rows) {
474
+ if (row.name === 'help') continue;
475
+ byName.set(row.name, row);
476
+ program.command(row.name);
477
+ }
478
+ const help = program.configureHelp();
479
+ program.configureHelp({
480
+ ...help,
481
+ subcommandTerm: cmd =>
482
+ byName.get(cmd.name())?.term ??
483
+ Help.prototype.subcommandTerm.call(program.createHelp(), cmd),
484
+ subcommandDescription: cmd =>
485
+ byName.get(cmd.name())?.description ??
486
+ Help.prototype.subcommandDescription.call(program.createHelp(), cmd),
487
+ });
488
+ }
489
+
401
490
  const SETUP_NUDGE_EXEMPT = new Set(['init', 'agent-docs']);
402
491
 
403
492
  /**
@@ -594,6 +683,7 @@ export async function createProgram({argv} = {}) {
594
683
  program.help();
595
684
  });
596
685
  markReportsResult(program);
686
+ resolveDeepHelp(program);
597
687
 
598
688
  /**
599
689
  * Pre-action hook: gate --json BEFORE any command body runs.
@@ -809,7 +899,9 @@ export async function createProgram({argv} = {}) {
809
899
  });
810
900
 
811
901
  const loads = argv == null ? null : commandsForArgs(program, argv);
812
- for (const cmd of commands) {
902
+ const listed = argv != null && printsRootHelp(argv) ? storedCommandList() : null;
903
+ if (listed) listStoredCommands(program, listed);
904
+ for (const cmd of listed ? [] : commands) {
813
905
  if (loads != null && !loads.has(cmd.name)) continue;
814
906
  try {
815
907
  const mod = await import(cmd.path);
@@ -188,6 +188,7 @@ function commanderCodeToErrorCode(commanderCode, message) {
188
188
  case 'commander.unknownOption':
189
189
  return ERROR_CODES.ERR_INVALID_OPTION;
190
190
  case 'commander.missingArgument':
191
+ case 'commander.optionMissingArgument':
191
192
  case 'commander.missingMandatoryOptionValue':
192
193
  return ERROR_CODES.ERR_MISSING_ARGUMENT;
193
194
  case 'commander.excessArguments':
@@ -249,6 +250,8 @@ function applyShimRecursively(cmd) {
249
250
  } catch {
250
251
  // Never let recording interfere with the error path.
251
252
  }
253
+ // The error handler names the rejected command's usage from it.
254
+ /** @type {any} */ (err)[REJECTED_COMMAND] = cmd;
252
255
  throw err;
253
256
  });
254
257
  cmd.configureOutput({
@@ -276,6 +279,25 @@ function applyShimRecursively(cmd) {
276
279
  }
277
280
  }
278
281
 
282
+ /** Carries the command Commander rejected from exitOverride to the error handler. */
283
+ const REJECTED_COMMAND = Symbol.for('astryx.jsonShim.rejectedCommand');
284
+
285
+ /**
286
+ * The usage line of the command a parse error came from, as a suggestion, for
287
+ * an option given without its value.
288
+ * @param {unknown} err
289
+ * @param {string} code
290
+ * @returns {import('../../../foundation/response/base').Suggestion[] | undefined}
291
+ */
292
+ function usageSuggestion(err, code) {
293
+ if (code !== 'commander.optionMissingArgument') return undefined;
294
+ const cmd = /** @type {any} */ (err)?.[REJECTED_COMMAND];
295
+ if (!cmd) return undefined;
296
+ const parts = [];
297
+ for (let node = cmd; node; node = node.parent) parts.unshift(node.name());
298
+ return [{name: `${parts.join(' ')} ${cmd.usage()}`.trim(), reason: 'usage'}];
299
+ }
300
+
279
301
  /** Marks a command whose `command`/`addCommand` already self-install the shim. */
280
302
  const SELF_INSTALLING = Symbol.for('astryx.jsonShim.selfInstalling');
281
303
 
@@ -448,12 +470,18 @@ export function handleCommanderError(err) {
448
470
  // Real error paths. Strip Commander's "error: " prefix once: in the envelope
449
471
  // the key is already `error`, and in text mode the Astryx prefix replaces it.
450
472
  const cleaned = message.replace(/^error:\s*/i, '');
473
+ const suggestions = usageSuggestion(err, code);
451
474
  if (jsonActive()) {
452
- emitJsonError(cleaned, undefined, commanderCodeToErrorCode(code, cleaned));
475
+ emitJsonError(
476
+ cleaned,
477
+ suggestions,
478
+ commanderCodeToErrorCode(code, cleaned),
479
+ );
453
480
  } else {
454
481
  // Commander's own line was suppressed above, so a parse failure reads the
455
482
  // same as every other CLI error — the `Error: …` line cliError prints.
456
483
  process.stderr.write(`Error: ${cleaned}\n`);
484
+ if (suggestions) process.stderr.write(`Usage: ${suggestions[0].name}\n`);
457
485
  }
458
486
  process.exit(exitCode || 1);
459
487
  }
@@ -159,12 +159,26 @@ export class Project {
159
159
  * ejects share one discovery seam. A broken integration theme contribution is
160
160
  * reported without hiding the package's other valid kinds.
161
161
  *
162
- * @param {{includeLocal?: boolean}} [options]
162
+ * With `skipBrokenLocal`, a local theme folder that fails validation is
163
+ * left out and recorded for `skippedLocalThemes()`, so one broken folder
164
+ * does not hide every other theme.
165
+ *
166
+ * @param {{includeLocal?: boolean, skipBrokenLocal?: boolean}} [options]
163
167
  * @returns {Promise<import('../discovery/theme-discovery.mjs').DiscoveredTheme[]>}
164
168
  */
165
- themes({ includeLocal }?: {
169
+ themes({ includeLocal, skipBrokenLocal }?: {
166
170
  includeLocal?: boolean;
171
+ skipBrokenLocal?: boolean;
167
172
  }): Promise<import("../discovery/theme-discovery.mjs").DiscoveredTheme[]>;
173
+ /**
174
+ * Local theme folders `themes({skipBrokenLocal: true})` left out, with why.
175
+ * @returns {Array<{slug: string, path: string, reason: string}>}
176
+ */
177
+ skippedLocalThemes(): Array<{
178
+ slug: string;
179
+ path: string;
180
+ reason: string;
181
+ }>;
168
182
  /**
169
183
  * Installed icon sets, the sets withdrawn and why, and the project's icon
170
184
  * set (AST-084 FR7, FR8). Sets come from each loaded integration's
@@ -35,6 +35,7 @@
35
35
 
36
36
  import * as fs from 'node:fs';
37
37
  import * as path from 'node:path';
38
+ import {LOCAL_THEME_ROOT} from './theme-state.mjs';
38
39
  import {loadModuleWithParser} from '../fs/module-loader.mjs';
39
40
  import {findConfigPath} from './config-path.mjs';
40
41
  import {parseConfig} from '../../authoring/config/parse.mjs';
@@ -324,7 +325,6 @@ function readPackageJson(dir) {
324
325
  * @typedef {import('../integrations/issue').AstryxIntegrationIssue & {package: string}} ProjectIntegrationIssue
325
326
  */
326
327
 
327
-
328
328
  /** Default issue tracker used when neither config nor integration routes one. */
329
329
  export const DEFAULT_ISSUES_URL =
330
330
  'https://github.com/meta/astryx/issues/new';
@@ -364,7 +364,6 @@ function inheritsIntegrationDebug(projectDir) {
364
364
  }
365
365
  }
366
366
 
367
-
368
367
  /**
369
368
  * The provider ledger each loaded Project resolved, kept off the class so it
370
369
  * is not part of the Project API.
@@ -419,6 +418,8 @@ export class Project {
419
418
  #core = 'any';
420
419
  /** @type {ProjectIntegrationIssue[]} */
421
420
  #issues = [];
421
+ /** @type {Array<{slug: string, path: string, reason: string}>} */
422
+ #skippedLocalThemes = [];
422
423
  /**
423
424
  * Loaded integrations whose issues have already been collected (via a
424
425
  * discovery method or a direct issues() validation), so issues() can fill in
@@ -925,14 +926,39 @@ export class Project {
925
926
  * ejects share one discovery seam. A broken integration theme contribution is
926
927
  * reported without hiding the package's other valid kinds.
927
928
  *
928
- * @param {{includeLocal?: boolean}} [options]
929
+ * With `skipBrokenLocal`, a local theme folder that fails validation is
930
+ * left out and recorded for `skippedLocalThemes()`, so one broken folder
931
+ * does not hide every other theme.
932
+ *
933
+ * @param {{includeLocal?: boolean, skipBrokenLocal?: boolean}} [options]
929
934
  * @returns {Promise<import('../discovery/theme-discovery.mjs').DiscoveredTheme[]>}
930
935
  */
931
- async themes({includeLocal = true} = {}) {
932
- return this.#memo(includeLocal ? 'themes' : 'themes:external', async () => {
936
+ async themes({includeLocal = true, skipBrokenLocal = false} = {}) {
937
+ const kind = !includeLocal
938
+ ? 'themes:external'
939
+ : skipBrokenLocal
940
+ ? 'themes:skip-broken'
941
+ : 'themes';
942
+ return this.#memo(kind, async () => {
933
943
  const themes = discoverBundledThemes();
934
944
  const projectDir = findPackageRoot(this.#cwd) ?? this.#cwd;
935
- if (includeLocal) themes.push(...discoverLocalThemes(projectDir));
945
+ if (includeLocal) {
946
+ themes.push(
947
+ ...discoverLocalThemes(projectDir, undefined, {
948
+ onFolderError: skipBrokenLocal
949
+ ? (slug, error) =>
950
+ this.#skippedLocalThemes.push({
951
+ slug,
952
+ path: path.posix.join(
953
+ LOCAL_THEME_ROOT.replace(/^\.\//, ''),
954
+ slug,
955
+ ),
956
+ reason: error.message,
957
+ })
958
+ : undefined,
959
+ }),
960
+ );
961
+ }
936
962
 
937
963
  for (const integration of this.#loadedIntegrations) {
938
964
  await this.#collectIssues(integration);
@@ -953,6 +979,14 @@ export class Project {
953
979
  });
954
980
  }
955
981
 
982
+ /**
983
+ * Local theme folders `themes({skipBrokenLocal: true})` left out, with why.
984
+ * @returns {Array<{slug: string, path: string, reason: string}>}
985
+ */
986
+ skippedLocalThemes() {
987
+ return this.#skippedLocalThemes.map(entry => ({...entry}));
988
+ }
989
+
956
990
  /**
957
991
  * Installed icon sets, the sets withdrawn and why, and the project's icon
958
992
  * set (AST-084 FR7, FR8). Sets come from each loaded integration's
@@ -17,6 +17,15 @@ export function findThemeProject(cwd: string): {
17
17
  * @param {string} owner
18
18
  */
19
19
  export function isLocalThemeOwner(owner: string): boolean;
20
+ /**
21
+ * The theme editor's record for the theme in `dir`, when the editor made it:
22
+ * the folder `<slug>/` holds `<slug>.settings.json`. The editor owns every
23
+ * theme file in that folder and regenerates it from the record, so eject and
24
+ * template never write there. Another `*.settings.json` is not the editor's.
25
+ * @param {string} dir
26
+ * @returns {string | null} the record's file name
27
+ */
28
+ export function editorThemeRecord(dir: string): string | null;
20
29
  /** @param {string} projectDir */
21
30
  export function projectUsesTypeScript(projectDir: string): boolean;
22
31
  /**
@@ -62,7 +62,26 @@ export function findThemeProject(cwd) {
62
62
  * @param {string} owner
63
63
  */
64
64
  export function isLocalThemeOwner(owner) {
65
- return owner.startsWith('./') || owner.startsWith('../') || path.isAbsolute(owner);
65
+ return (
66
+ owner.startsWith('./') || owner.startsWith('../') || path.isAbsolute(owner)
67
+ );
68
+ }
69
+
70
+ /**
71
+ * The theme editor's record for the theme in `dir`, when the editor made it:
72
+ * the folder `<slug>/` holds `<slug>.settings.json`. The editor owns every
73
+ * theme file in that folder and regenerates it from the record, so eject and
74
+ * template never write there. Another `*.settings.json` is not the editor's.
75
+ * @param {string} dir
76
+ * @returns {string | null} the record's file name
77
+ */
78
+ export function editorThemeRecord(dir) {
79
+ const record = `${path.basename(path.resolve(dir))}.settings.json`;
80
+ try {
81
+ return fs.statSync(path.join(dir, record)).isFile() ? record : null;
82
+ } catch {
83
+ return null;
84
+ }
66
85
  }
67
86
 
68
87
  /** @param {string} projectDir */
@@ -234,11 +234,20 @@ export function extractComponents(pagePath: string): string[];
234
234
  /**
235
235
  * The components a template source composes. A surface that returns rewritten
236
236
  * source lists the components of that source, so a component the rewrite
237
- * removed is not listed.
237
+ * removed is not listed. A template Astryx ships answers from its stored list
238
+ * (TEMPLATE_COMPONENTS_FILE), which holds what parsing it returns; any other
239
+ * source, such as an integration's template, is parsed.
238
240
  * @param {string} src
239
241
  * @returns {string[]}
240
242
  */
241
243
  export function componentsInSource(src: string): string[];
244
+ /**
245
+ * The components a template source composes, read from its syntax tree (see
246
+ * componentsInSource).
247
+ * @param {string} src
248
+ * @returns {string[]}
249
+ */
250
+ export function parsedComponents(src: string): string[];
242
251
  /**
243
252
  * Every name componentsInSource can return for `src`, read without parsing
244
253
  * it, or null when it cannot be bounded so. It keeps the tag names a parse
@@ -264,6 +273,8 @@ export const MARKED_VIDEO_PLACEHOLDER: "data:,placeholder-video-add-your-own";
264
273
  * {@link replaceDemoContent}).
265
274
  */
266
275
  export const DEMO_CONTENT_MODULE: "@astryx-docs/demo-content";
276
+ /** Where the component lists of the templates Astryx ships are stored. */
277
+ export const TEMPLATE_COMPONENTS_FILE: string;
267
278
  /**
268
279
  * A discovered template (page or block), normalized across core, external, and
269
280
  * integration sources. Not every source populates every field, so
@@ -27,6 +27,7 @@ import * as path from 'node:path';
27
27
  import {createRequire} from 'node:module';
28
28
  import {readDocView} from '../doc-compiler/read.mjs';
29
29
  import {importDocModule} from '../doc-compiler/import.mjs';
30
+ import {readStore, storedKey} from '../doc-compiler/stored-docs.mjs';
30
31
  import {CLI_ROOT, discoverExternalPackages} from '../fs/paths.mjs';
31
32
  import {listDirEntries} from '../fs/listing-cache.mjs';
32
33
  import {CORE_PROVIDER_ID} from '../identity/providers.mjs';
@@ -2096,11 +2097,33 @@ export function extractComponents(pagePath) {
2096
2097
  /**
2097
2098
  * The components a template source composes. A surface that returns rewritten
2098
2099
  * source lists the components of that source, so a component the rewrite
2099
- * removed is not listed.
2100
+ * removed is not listed. A template Astryx ships answers from its stored list
2101
+ * (TEMPLATE_COMPONENTS_FILE), which holds what parsing it returns; any other
2102
+ * source, such as an integration's template, is parsed.
2100
2103
  * @param {string} src
2101
2104
  * @returns {string[]}
2102
2105
  */
2103
2106
  export function componentsInSource(src) {
2107
+ const known = readStore(TEMPLATE_COMPONENTS_FILE).get(storedKey(src));
2108
+ if (known) return [...known];
2109
+ return parsedComponents(src);
2110
+ }
2111
+
2112
+ /** Where the component lists of the templates Astryx ships are stored. */
2113
+ export const TEMPLATE_COMPONENTS_FILE = path.join(
2114
+ CLI_ROOT,
2115
+ 'assets',
2116
+ 'templates',
2117
+ 'components.generated.json',
2118
+ );
2119
+
2120
+ /**
2121
+ * The components a template source composes, read from its syntax tree (see
2122
+ * componentsInSource).
2123
+ * @param {string} src
2124
+ * @returns {string[]}
2125
+ */
2126
+ export function parsedComponents(src) {
2104
2127
  // Match JSX opening tags, e.g. `<Section` or the legacy `<XDSSection`.
2105
2128
  // Templates author bare component names post un-prefix migration,
2106
2129
  // so the `XDS` prefix is optional. Anchoring on the `<`
@@ -4,6 +4,13 @@
4
4
  /**
5
5
  * Extract bare (non-relative) package names from ES import statements.
6
6
  *
7
+ * Only real module specifiers count: `import … from`, a side-effect
8
+ * `import '…'`, `export … from`, a dynamic `import('…')` or `require('…')`
9
+ * with a string, and a type `import('…')`.
10
+ * Words in comments, strings and JSX text never count, and a specifier that
11
+ * is not an npm package name (`@/components`, `~/lib`, `#internal`, a word
12
+ * with spaces) is an alias or a typo, not a package to install.
13
+ *
7
14
  * @param {string} source Template source code
8
15
  * @returns {Set<string>} Unique package names (scoped packages normalized to
9
16
  * `@scope/name`, unscoped to the first path segment).
@@ -18,6 +18,7 @@
18
18
  import * as fs from 'node:fs';
19
19
  import * as path from 'node:path';
20
20
  import module from 'node:module';
21
+ import {parseTemplateSource, walk} from './template-source-tree.mjs';
21
22
  import {CLI_ROOT, findWorkspaceRoot} from '../fs/paths.mjs';
22
23
  import {detectStylingSystem} from '../agent-docs/agent-docs.mjs';
23
24
  import {
@@ -35,34 +36,142 @@ const STYLEX_RUNTIME = '@stylexjs/stylex';
35
36
  // Node builtins: anything with a `node:` prefix or in builtinModules.
36
37
  const NODE_BUILTINS = new Set(module.builtinModules);
37
38
 
39
+ /**
40
+ * A package name npm accepts, optionally scoped. Legacy names keep capitals
41
+ * (`JSONStream`). A name has no `~`, so `~/lib` is a path alias, as are
42
+ * `@/components` and `#internal`.
43
+ */
44
+ const NPM_NAME = /^(?:@[\w.-]+\/[\w-][\w.-]*|[A-Za-z0-9][\w.-]*)$/;
45
+
38
46
  /**
39
47
  * Extract bare (non-relative) package names from ES import statements.
40
48
  *
49
+ * Only real module specifiers count: `import … from`, a side-effect
50
+ * `import '…'`, `export … from`, a dynamic `import('…')` or `require('…')`
51
+ * with a string, and a type `import('…')`.
52
+ * Words in comments, strings and JSX text never count, and a specifier that
53
+ * is not an npm package name (`@/components`, `~/lib`, `#internal`, a word
54
+ * with spaces) is an alias or a typo, not a package to install.
55
+ *
41
56
  * @param {string} source Template source code
42
57
  * @returns {Set<string>} Unique package names (scoped packages normalized to
43
58
  * `@scope/name`, unscoped to the first path segment).
44
59
  */
45
60
  export function extractImportedPackages(source) {
46
- // Matches `import … from '<specifier>'`, `import '<specifier>'`, and
47
- // dynamic `import('<specifier>')`. Only bare specifiers (not starting with
48
- // `.` or `/`).
49
- const re = /(?:from\s+|import\s*\(?)['"]((?:@[^/'"]+\/)?[^./'"@][^'"]*)['"]/g;
50
61
  /** @type {Set<string>} */
51
62
  const pkgs = new Set();
52
- let m;
53
- while ((m = re.exec(source)) !== null) {
54
- const spec = m[1];
63
+ for (const spec of moduleSpecifiers(source)) {
55
64
  // Skip Node builtins: `node:fs`, `fs`, `fs/promises`, etc.
56
65
  if (spec.startsWith('node:')) continue;
66
+ if (spec.startsWith('.') || spec.startsWith('/')) continue;
57
67
  const name = spec.startsWith('@')
58
68
  ? spec.split('/').slice(0, 2).join('/')
59
69
  : spec.split('/')[0];
60
- if (NODE_BUILTINS.has(name)) continue;
70
+ if (NODE_BUILTINS.has(name) || !NPM_NAME.test(name)) continue;
61
71
  pkgs.add(name);
62
72
  }
63
73
  return pkgs;
64
74
  }
65
75
 
76
+ /**
77
+ * The module specifiers a source imports or re-exports, read from its syntax
78
+ * tree. A source the parser cannot read is scanned line by line instead, with
79
+ * comments removed, so only statements that start a line count.
80
+ * @param {string} source
81
+ * @returns {string[]}
82
+ */
83
+ function moduleSpecifiers(source) {
84
+ let file;
85
+ try {
86
+ file = parseTemplateSource(source, {errorRecovery: true});
87
+ } catch {
88
+ return scannedSpecifiers(source);
89
+ }
90
+ /** @type {string[]} */
91
+ const specs = [];
92
+ /** @param {any} literal */
93
+ const add = literal => {
94
+ if (literal?.type === 'StringLiteral') specs.push(literal.value);
95
+ };
96
+ walk(file.program, (/** @type {any} */ node) => {
97
+ if (
98
+ node.type === 'ImportDeclaration' ||
99
+ node.type === 'ExportNamedDeclaration' ||
100
+ node.type === 'ExportAllDeclaration'
101
+ ) {
102
+ add(node.source);
103
+ } else if (
104
+ node.type === 'CallExpression' &&
105
+ node.callee?.type === 'Import'
106
+ ) {
107
+ add(node.arguments?.[0]);
108
+ } else if (
109
+ node.type === 'CallExpression' &&
110
+ node.callee?.type === 'Identifier' &&
111
+ node.callee.name === 'require'
112
+ ) {
113
+ add(node.arguments?.[0]);
114
+ } else if (node.type === 'ImportExpression') {
115
+ add(node.source);
116
+ } else if (node.type === 'TSImportType') {
117
+ // `type O = import('chart-lib').Options`
118
+ add(
119
+ node.argument?.type === 'TSLiteralType'
120
+ ? node.argument.literal
121
+ : node.argument,
122
+ );
123
+ }
124
+ });
125
+ return specs;
126
+ }
127
+
128
+ /**
129
+ * A source with its comments removed. Strings and template literals are kept
130
+ * whole, so a `/*` or `//` inside one (`'images/*'`) does not start a comment.
131
+ * @param {string} source
132
+ * @returns {string}
133
+ */
134
+ function withoutComments(source) {
135
+ let out = '';
136
+ for (let i = 0; i < source.length; i += 1) {
137
+ const ch = source[i];
138
+ const next = source[i + 1];
139
+ if (ch === '/' && next === '/') {
140
+ while (i < source.length && source[i] !== '\n') i += 1;
141
+ out += '\n';
142
+ } else if (ch === '/' && next === '*') {
143
+ const end = source.indexOf('*/', i + 2);
144
+ i = end === -1 ? source.length : end + 1;
145
+ } else if (ch === "'" || ch === '"' || ch === '`') {
146
+ let j = i + 1;
147
+ while (j < source.length && source[j] !== ch) {
148
+ if (source[j] === '\\') j += 1;
149
+ else if (ch !== '`' && source[j] === '\n') break;
150
+ j += 1;
151
+ }
152
+ out += source.slice(i, j + 1);
153
+ i = j;
154
+ } else {
155
+ out += ch;
156
+ }
157
+ }
158
+ return out;
159
+ }
160
+
161
+ /** @param {string} source @returns {string[]} */
162
+ function scannedSpecifiers(source) {
163
+ const code = withoutComments(source);
164
+ // A statement starts a line: `import '…'`, or `import`/`export` with a
165
+ // clause, which may span lines, then `from '…'`.
166
+ const re =
167
+ /^\s*import\s*['"]([^'"\n]+)['"]|^\s*(?:import|export)\b[^'";]*?\bfrom\s*['"]([^'"\n]+)['"]|\bimport\(\s*['"]([^'"\n]+)['"]\s*\)/gm;
168
+ /** @type {string[]} */
169
+ const specs = [];
170
+ let m;
171
+ while ((m = re.exec(code)) !== null) specs.push(m[1] ?? m[2] ?? m[3]);
172
+ return specs;
173
+ }
174
+
66
175
  /** @type {Record<string, string>} */
67
176
  const ADD_VERB = {
68
177
  pnpm: 'pnpm add',
@@ -5,9 +5,13 @@
5
5
  * Parse template source as TSX. Babel loads on first use, so a command that
6
6
  * only lists templates never pays for it.
7
7
  * @param {string} source
8
+ * @param {{errorRecovery?: boolean}} [options] `errorRecovery`: keep parsing
9
+ * past a recoverable error, for a reader that only needs part of the tree
8
10
  * @returns {any} The file node.
9
11
  */
10
- export function parseTemplateSource(source: string): any;
12
+ export function parseTemplateSource(source: string, { errorRecovery }?: {
13
+ errorRecovery?: boolean;
14
+ }): any;
11
15
  /**
12
16
  * The module scope of a parsed file. Its bindings, and the scope of each path
13
17
  * a traversal visits, resolve a name to the declaration it reads, so a rewrite
@@ -7,8 +7,8 @@
7
7
  *
8
8
  * @input Template source text
9
9
  * @output Its parsed tree, node visits, names, and module scope
10
- * @position packages/cli/foundation/discovery — read by template-icons and by
11
- * the demo-content replacement in template-adapter
10
+ * @position packages/cli/foundation/discovery — read by template-icons, by
11
+ * the demo-content replacement in template-adapter, and by template-needs
12
12
  */
13
13
 
14
14
  import {createRequire} from 'node:module';
@@ -24,16 +24,18 @@ let babelCore;
24
24
  * Parse template source as TSX. Babel loads on first use, so a command that
25
25
  * only lists templates never pays for it.
26
26
  * @param {string} source
27
+ * @param {{errorRecovery?: boolean}} [options] `errorRecovery`: keep parsing
28
+ * past a recoverable error, for a reader that only needs part of the tree
27
29
  * @returns {any} The file node.
28
30
  */
29
- export function parseTemplateSource(source) {
31
+ export function parseTemplateSource(source, {errorRecovery = false} = {}) {
30
32
  babelParser ??= /** @type {typeof import('@babel/parser')} */ (
31
33
  require('@babel/parser')
32
34
  );
33
35
  return babelParser.parse(source, {
34
36
  sourceType: 'module',
35
37
  plugins: ['jsx', 'typescript'],
36
- errorRecovery: false,
38
+ errorRecovery,
37
39
  });
38
40
  }
39
41