@astryxdesign/cli 0.7.2-canary.020e1fe → 0.7.2-canary.081ccea

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 (133) hide show
  1. package/README.md +62 -62
  2. package/api/component/_adapter.d.mts +31 -0
  3. package/api/component/_adapter.mjs +116 -0
  4. package/api/component/component.mjs +60 -10
  5. package/api/component/doc-links.test.mjs +386 -0
  6. package/api/discover/_adapter.d.mts +119 -12
  7. package/api/discover/_adapter.mjs +449 -10
  8. package/api/discover/_adapter.test.mjs +599 -17
  9. package/api/discover/_catalog-view.d.mts +16 -5
  10. package/api/discover/_catalog-view.mjs +32 -8
  11. package/api/discover/detail/doc/doc.mjs +9 -1
  12. package/api/discover/discover.d.mts +11 -0
  13. package/api/discover/discover.doc.mjs +7 -6
  14. package/api/discover/discover.mjs +107 -19
  15. package/api/discover/discover.type.d.mts +18 -7
  16. package/api/discover/discover.type.mjs +15 -7
  17. package/api/discover/list/list.d.mts +4 -3
  18. package/api/discover/list/list.mjs +17 -10
  19. package/api/docs/_adapter.d.mts +63 -0
  20. package/api/docs/_adapter.mjs +309 -16
  21. package/api/docs/integration-tree.test.mjs +22 -0
  22. package/api/docs/list/list.mjs +12 -2
  23. package/api/doctor/theme-checks.test.mjs +136 -0
  24. package/api/gap-report/gap-report.d.mts +3 -0
  25. package/api/gap-report/gap-report.doc.mjs +11 -3
  26. package/api/gap-report/gap-report.mjs +152 -48
  27. package/api/gap-report/gap-report.test.mjs +233 -0
  28. package/api/gap-report/gap-report.type.d.mts +41 -0
  29. package/api/gap-report/gap-report.type.mjs +18 -0
  30. package/api/integration/_adapter.d.mts +33 -0
  31. package/api/integration/_adapter.mjs +58 -0
  32. package/api/integration/authoring-checks.mjs +98 -3
  33. package/api/integration/authoring-checks.test.mjs +769 -0
  34. package/api/integration/authoring-checks.type.d.mts +134 -0
  35. package/api/integration/authoring-checks.type.mjs +60 -1
  36. package/api/integration/integrationComponentConflicts.doc.mjs +3 -1
  37. package/api/integration/integrationDocConflicts.doc.mjs +22 -5
  38. package/api/integration/pack-check.mjs +296 -7
  39. package/api/integration/pack-check.test.mjs +367 -0
  40. package/api/integration/validate-integration-fixes.test.mjs +67 -0
  41. package/api/integration/validate-integration.mjs +28 -3
  42. package/api/integration/validate-integration.test.mjs +77 -8
  43. package/api/integration/validateIntegration.doc.mjs +1 -1
  44. package/api/search/search.mjs +2 -1
  45. package/api/upgrade/_adapter.d.mts +40 -2
  46. package/api/upgrade/_adapter.mjs +117 -4
  47. package/api/upgrade/run/cli-behind-core.test.mjs +438 -0
  48. package/api/upgrade/run/run.mjs +30 -1
  49. package/api/upgrade/status/status.d.mts +21 -5
  50. package/api/upgrade/status/status.mjs +45 -8
  51. package/api/upgrade/upgrade.doc.mjs +5 -3
  52. package/api/upgrade/upgrade.type.d.mts +23 -0
  53. package/api/upgrade/upgrade.type.mjs +16 -1
  54. package/assets/codemods/runner.mjs +7 -1
  55. package/assets/discover/official-packages.json +367 -0
  56. package/assets/docs/author-a-theme.doc.mjs +2 -2
  57. package/assets/docs/browser-support.doc.mjs +1 -1
  58. package/assets/docs/styling-overview.doc.mjs +1 -1
  59. package/assets/docs/theme.doc.mjs +1 -1
  60. package/assets/docs/tree/add-a-topic.doc.mjs +3 -3
  61. package/assets/docs/tree/check-the-props.doc.mjs +7 -2
  62. package/assets/docs/tree/check-your-docs.doc.mjs +15 -3
  63. package/assets/docs/tree/checks.doc.mjs +5 -5
  64. package/assets/docs/tree/debug-and-gap-reports.doc.mjs +25 -5
  65. package/assets/docs/tree/document-the-theme.doc.mjs +2 -2
  66. package/assets/docs/tree/layout-spacing.doc.mjs +2 -3
  67. package/assets/docs/tree/layout.doc.mjs +6 -6
  68. package/assets/docs/tree/migration-setup.doc.mjs +2 -2
  69. package/assets/docs/tree/publishing.doc.mjs +3 -3
  70. package/assets/docs/tree/quick-start.doc.mjs +2 -2
  71. package/assets/docs/tree/sections-and-placement.doc.mjs +2 -2
  72. package/assets/docs/tree/template-doc-overview.doc.mjs +1 -1
  73. package/assets/docs/tree/troubleshooting.doc.mjs +5 -5
  74. package/assets/docs/tree/upgrading.doc.mjs +1 -1
  75. package/authoring/discover/discover.doc.mjs +1 -1
  76. package/authoring/doctypes/component/component.doc.mjs +1 -1
  77. package/authoring/doctypes/component/type.ts +8 -0
  78. package/authoring/doctypes/hook/type.ts +4 -0
  79. package/clients/cli/commands/discover.broken-integration.test.mjs +4 -1
  80. package/clients/cli/commands/discover.doc.mjs +1 -1
  81. package/clients/cli/commands/discover.mjs +144 -93
  82. package/clients/cli/commands/discover.no-source.test.mjs +447 -33
  83. package/clients/cli/commands/discover.sources.test.mjs +20 -1
  84. package/clients/cli/commands/doctor-integration-components.doc.mjs +3 -2
  85. package/clients/cli/commands/doctor-integration-docs.doc.mjs +19 -5
  86. package/clients/cli/commands/doctor-integration.test.mjs +48 -1
  87. package/clients/cli/commands/doctor.mjs +91 -5
  88. package/clients/cli/commands/gap-report.doc.mjs +14 -2
  89. package/clients/cli/commands/gap-report.mjs +24 -2
  90. package/clients/cli/commands/gap-report.test.mjs +79 -0
  91. package/clients/cli/commands/integration-authoring.test.mjs +46 -0
  92. package/clients/cli/commands/integration-check.test.mjs +144 -0
  93. package/clients/cli/commands/integration.mjs +12 -7
  94. package/clients/cli/commands/json-contract.test.mjs +5 -1
  95. package/clients/cli/commands/upgrade.doc.mjs +14 -0
  96. package/clients/cli/commands/upgrade.older-cli.test.mjs +160 -0
  97. package/foundation/discovery/copied-passages.d.mts +216 -0
  98. package/foundation/discovery/copied-passages.mjs +720 -0
  99. package/foundation/discovery/copied-passages.test.mjs +124 -0
  100. package/foundation/discovery/doc-consistency.d.mts +34 -0
  101. package/foundation/discovery/doc-consistency.mjs +513 -0
  102. package/foundation/discovery/doc-consistency.test.mjs +347 -0
  103. package/foundation/discovery/doc-fluff.d.mts +112 -0
  104. package/foundation/discovery/doc-fluff.mjs +328 -0
  105. package/foundation/discovery/doc-fluff.test.mjs +142 -0
  106. package/foundation/discovery/doc-types.mjs +12 -5
  107. package/foundation/discovery/doc-types.test.mjs +46 -2
  108. package/foundation/discovery/docs-discovery.d.mts +7 -0
  109. package/foundation/discovery/docs-discovery.mjs +26 -2
  110. package/foundation/discovery/prop-drift.d.mts +25 -6
  111. package/foundation/discovery/prop-drift.mjs +171 -6
  112. package/foundation/discovery/prop-drift.test.mjs +65 -0
  113. package/foundation/discovery/stray-pointers.d.mts +52 -0
  114. package/foundation/discovery/stray-pointers.mjs +293 -0
  115. package/foundation/discovery/stray-pointers.test.mjs +86 -0
  116. package/foundation/doc-compiler/doc-loads.test.mjs +16 -0
  117. package/foundation/doc-compiler/links.d.mts +32 -0
  118. package/foundation/doc-compiler/links.mjs +163 -26
  119. package/foundation/doc-compiler/links.test.mjs +97 -4
  120. package/foundation/doc-compiler/tree.mjs +30 -1
  121. package/foundation/doc-compiler/tree.test.mjs +7 -0
  122. package/foundation/env/package-manager.d.mts +32 -0
  123. package/foundation/env/package-manager.mjs +47 -0
  124. package/foundation/env/package-manager.test.mjs +194 -7
  125. package/foundation/fs/module-loader.d.mts +2 -1
  126. package/foundation/fs/module-loader.mjs +60 -4
  127. package/foundation/fs/module-loader.test.mjs +194 -0
  128. package/foundation/integrations/contribution-inventory.d.mts +11 -0
  129. package/foundation/integrations/contribution-inventory.mjs +50 -2
  130. package/foundation/integrations/issue.ts +6 -0
  131. package/foundation/integrations/validate-contributions.mjs +30 -1
  132. package/foundation/response/response-types.doc.mjs +10 -9
  133. package/package.json +11 -11
@@ -8,8 +8,10 @@
8
8
  import {describe, expect, it} from 'vitest';
9
9
  import {
10
10
  linkBlocks,
11
+ linkFields,
11
12
  linkSections,
12
13
  parseLinkTarget,
14
+ textFields,
13
15
  unlinkText,
14
16
  } from './links.mjs';
15
17
 
@@ -58,14 +60,20 @@ describe('linkBlocks', () => {
58
60
  const {content, problems} = await linkBlocks(
59
61
  [
60
62
  {type: 'prose', text: 'Check it with {@link command:doctor}.'},
61
- {type: 'list', style: 'unordered', items: ['See {@link @acme/kit:generic:setup}']},
63
+ {
64
+ type: 'list',
65
+ style: 'unordered',
66
+ items: ['See {@link @acme/kit:generic:setup}'],
67
+ },
62
68
  {type: 'table', headers: ['Doc'], rows: [['{@link command:doctor}']]},
63
69
  {type: 'code', lang: 'js', code: '{@link command:doctor}'},
64
70
  ],
65
71
  resolve,
66
72
  );
67
73
  expect(problems).toEqual([]);
68
- expect(content[0].text).toBe('Check it with `astryx docs cli/commands/doctor`.');
74
+ expect(content[0].text).toBe(
75
+ 'Check it with `astryx docs cli/commands/doctor`.',
76
+ );
69
77
  expect(content[1].items).toEqual(['See `astryx docs acme/setup`']);
70
78
  expect(content[2].rows).toEqual([['`astryx docs cli/commands/doctor`']]);
71
79
  // Code is an example: it is shown as written.
@@ -74,7 +82,12 @@ describe('linkBlocks', () => {
74
82
 
75
83
  it('shows a link written in code ticks as written', async () => {
76
84
  const {content, problems} = await linkBlocks(
77
- [{type: 'prose', text: 'Write `{@link <target>}` to link; {@link command:doctor} checks it.'}],
85
+ [
86
+ {
87
+ type: 'prose',
88
+ text: 'Write `{@link <target>}` to link; {@link command:doctor} checks it.',
89
+ },
90
+ ],
78
91
  resolve,
79
92
  );
80
93
  expect(problems).toEqual([]);
@@ -172,7 +185,10 @@ describe('linkBlocks', () => {
172
185
  },
173
186
  ],
174
187
  resolve,
175
- ).then(({sections, problems}) => ({content: sections[0].content, problems}));
188
+ ).then(({sections, problems}) => ({
189
+ content: sections[0].content,
190
+ problems,
191
+ }));
176
192
  expect(content[0].text).toBe('See {@link command:nope}.');
177
193
  expect(content[1].link).toBeNull();
178
194
  expect(problems.map(p => [p.section, p.target])).toEqual([
@@ -190,3 +206,80 @@ describe('unlinkText', () => {
190
206
  );
191
207
  });
192
208
  });
209
+
210
+ describe('linkFields', () => {
211
+ /** A component doc with a link in every kind of text field, and in code. */
212
+ const DOC = {
213
+ name: 'AcmeButton',
214
+ description: 'Run {@link command:doctor} first.',
215
+ usage: {
216
+ description: 'Set it up: {@link @acme/kit:generic:setup}.',
217
+ bestPractices: [
218
+ {guidance: true, description: 'Check with {@link command:doctor}.'},
219
+ ],
220
+ },
221
+ props: [
222
+ {
223
+ name: 'tone',
224
+ type: '{@link command:doctor}',
225
+ default: "'{@link command:doctor}'",
226
+ description: 'Like `{@link command:doctor}`, or {@link generic:nope}.',
227
+ },
228
+ ],
229
+ propDescriptions: {tone: 'See {@link command:doctor}.'},
230
+ examples: [
231
+ {label: 'From {@link command:doctor}', code: '{@link command:doctor}'},
232
+ ],
233
+ playground: {defaults: {label: '{@link command:doctor}'}},
234
+ };
235
+
236
+ it('resolves each text field and leaves names, types, defaults, and code as written', async () => {
237
+ const {doc, problems} = await linkFields(DOC, resolve);
238
+ expect(doc).toEqual({
239
+ ...DOC,
240
+ description: 'Run `astryx docs cli/commands/doctor` first.',
241
+ usage: {
242
+ description: 'Set it up: `astryx docs acme/setup`.',
243
+ bestPractices: [
244
+ {
245
+ guidance: true,
246
+ description: 'Check with `astryx docs cli/commands/doctor`.',
247
+ },
248
+ ],
249
+ },
250
+ props: [
251
+ {
252
+ ...DOC.props[0],
253
+ description:
254
+ 'Like `{@link command:doctor}`, or {@link generic:nope}.',
255
+ },
256
+ ],
257
+ propDescriptions: {tone: 'See `astryx docs cli/commands/doctor`.'},
258
+ examples: [
259
+ {
260
+ label: 'From `astryx docs cli/commands/doctor`',
261
+ code: '{@link command:doctor}',
262
+ },
263
+ ],
264
+ });
265
+ expect(problems).toEqual([
266
+ {
267
+ target: 'generic:nope',
268
+ message: expect.any(String),
269
+ field: 'props[0].description',
270
+ },
271
+ ]);
272
+ });
273
+
274
+ it('names the same text fields textFields reads', async () => {
275
+ const {problems} = await linkFields(DOC, async target => ({
276
+ problem: `no ${target}`,
277
+ }));
278
+ const fields = textFields(DOC)
279
+ .filter(({text}) => text.replace(/`[^`]*`/g, '').includes('{@link'))
280
+ .map(({field}) => field);
281
+ expect([...new Set(problems.map(problem => problem.field))]).toEqual(
282
+ fields,
283
+ );
284
+ });
285
+ });
@@ -242,7 +242,8 @@ export function buildDocsTree({namespaces, docs, topics = []}) {
242
242
  // without case, as topic names do, so `CLI` claims `cli`.
243
243
  const cliRoutes = new Set(topics.length > 0 ? [UNORGANIZED] : []);
244
244
  for (const topic of topics) {
245
- if (topic.provider === CLI_PROVIDER) cliRoutes.add(topic.name.toLowerCase());
245
+ if (topic.provider === CLI_PROVIDER)
246
+ cliRoutes.add(topic.name.toLowerCase());
246
247
  }
247
248
  // Every other name a topic answers to (the topics it replaced, directly or
248
249
  // through a chain) is that topic's route too: `astryx docs <name>` opens the
@@ -375,6 +376,34 @@ export function buildDocsTree({namespaces, docs, topics = []}) {
375
376
  return false;
376
377
  }
377
378
  const taken = byFoldedRoute.get(folded);
379
+ if (
380
+ taken &&
381
+ taken.provider === CLI_PROVIDER &&
382
+ node.provider !== CLI_PROVIDER &&
383
+ !node.generated
384
+ ) {
385
+ // Astryx's own doc keeps its route: name both docs as an author knows
386
+ // them, never by their ids, and say what to change.
387
+ const what = (/** @type {TreeNode} */ n) =>
388
+ n.kind === 'namespace'
389
+ ? 'namespace'
390
+ : n.kind === 'generic'
391
+ ? 'topic'
392
+ : `${n.kind} doc`;
393
+ const scope = String(node.provider).split('/').pop() ?? '';
394
+ const suggestion = `${
395
+ scope
396
+ .replace(/[^a-z0-9]+/gi, '-')
397
+ .replace(/^-|-$/g, '')
398
+ .toLowerCase() || 'my'
399
+ }-${node.name.toLowerCase()}`;
400
+ report(
401
+ 'duplicate_route',
402
+ at,
403
+ `The ${what(node)} "${node.name}" from ${node.provider} and Astryx's own ${what(taken)} "${taken.name}" both have the route "${node.route}", so \`astryx docs ${node.route}\` cannot open both. Fix: rename "${node.name}" (its \`name\` and its file), such as \`name: '${suggestion}'\`${node.route.includes('/') ? ', or place it elsewhere' : ''}.`,
404
+ );
405
+ return false;
406
+ }
378
407
  if (taken) {
379
408
  report(
380
409
  'duplicate_route',
@@ -171,6 +171,13 @@ describe('buildDocsTree', () => {
171
171
  ['duplicate_route', expect.stringContaining('takes the route "UNORGANIZED", which the CLI\'s own docs keep')],
172
172
  ]),
173
173
  );
174
+ // It names both docs as their authors know them, never by artifact id,
175
+ // and says what to change.
176
+ const taken = problems(tree).find(([, message]) => message.includes('route "CLI"'))?.[1];
177
+ expect(taken).toBe(
178
+ `The topic "CLI" from ${P} and Astryx's own namespace "cli" both have the route "CLI", so \`astryx docs CLI\` cannot open both. Fix: rename "CLI" (its \`name\` and its file), such as \`name: 'kit-cli'\`.`,
179
+ );
180
+ expect(taken).not.toContain('astryx:artifact');
174
181
  expect(tree.getFolded('THEME')?.provider).toBe(CLI);
175
182
  // A CLI topic whose own name has capitals keeps its route against a
176
183
  // lowercase namespace, although namespaces go into the tree first.
@@ -157,6 +157,38 @@ export function getCliInvocation(targetDir?: string): string;
157
157
  * @returns {string}
158
158
  */
159
159
  export function formatCliCommand(command: string, targetDir?: string): string;
160
+ /**
161
+ * Quote one argument of a printed command so the shell it is pasted into
162
+ * passes it on unchanged. Printed commands target a POSIX shell (sh, bash,
163
+ * zsh), and PowerShell on Windows; cmd.exe is not a target. A value made only
164
+ * of letters, digits and `@ / . _ -` (and, on Windows, a drive path's `:` and
165
+ * `\`) stays bare. Any other value gets single quotes, inside which both
166
+ * shells read `$`, backticks, `%`, `!`, spaces and double quotes literally. An
167
+ * embedded single quote is written `'\''` for a POSIX shell and doubled for
168
+ * PowerShell, which also ends a single-quoted string at the typographic
169
+ * quotes `‘ ’ ‚ ‛`, so those are doubled too (`Macy’s` → `'Macy’’s'`).
170
+ *
171
+ * @param {string} value
172
+ * @param {string} [platform] the `process.platform` the command is printed for
173
+ * @returns {string}
174
+ */
175
+ export function quoteCommandArgument(value: string, platform?: string): string;
176
+ /**
177
+ * A printed command that changes to `dir`, then runs `command` there, so it
178
+ * does the same work pasted from any folder. It runs `command` only when the
179
+ * change worked. For a POSIX shell: `cd <dir> && <command>`. For PowerShell
180
+ * on Windows: `cd -LiteralPath <dir> -ErrorAction Stop; <command>`, because
181
+ * `-LiteralPath` reads `[` and `]` in a folder name literally, and a failed
182
+ * change stops the line in Windows PowerShell 5.1, which has no `&&`, as in
183
+ * PowerShell 7.
184
+ *
185
+ * @param {string} dir an absolute folder
186
+ * @param {string} command the command to run there, its arguments already
187
+ * quoted with {@link quoteCommandArgument}
188
+ * @param {string} [platform] the `process.platform` the command is printed for
189
+ * @returns {string}
190
+ */
191
+ export function commandInFolder(dir: string, command: string, platform?: string): string;
160
192
  /** The published CLI package name — used for one-off (uninstalled) invocations. */
161
193
  export const CLI_PACKAGE: "@astryxdesign/cli";
162
194
  /** The CLI binary name — only resolves once the CLI is installed (or run via CLI_PACKAGE). */
@@ -512,3 +512,50 @@ export function formatCliCommand(command, targetDir) {
512
512
  const stem = getCliInvocation(targetDir);
513
513
  return sub ? `${stem} ${sub}` : stem;
514
514
  }
515
+
516
+ /**
517
+ * Quote one argument of a printed command so the shell it is pasted into
518
+ * passes it on unchanged. Printed commands target a POSIX shell (sh, bash,
519
+ * zsh), and PowerShell on Windows; cmd.exe is not a target. A value made only
520
+ * of letters, digits and `@ / . _ -` (and, on Windows, a drive path's `:` and
521
+ * `\`) stays bare. Any other value gets single quotes, inside which both
522
+ * shells read `$`, backticks, `%`, `!`, spaces and double quotes literally. An
523
+ * embedded single quote is written `'\''` for a POSIX shell and doubled for
524
+ * PowerShell, which also ends a single-quoted string at the typographic
525
+ * quotes `‘ ’ ‚ ‛`, so those are doubled too (`Macy’s` → `'Macy’’s'`).
526
+ *
527
+ * @param {string} value
528
+ * @param {string} [platform] the `process.platform` the command is printed for
529
+ * @returns {string}
530
+ */
531
+ export function quoteCommandArgument(value, platform = process.platform) {
532
+ const text = String(value);
533
+ if (platform === 'win32') {
534
+ if (/^[A-Za-z0-9@/._:\\-]+$/u.test(text)) return text;
535
+ return `'${text.replace(/['\u2018\u2019\u201A\u201B]/gu, quote => quote + quote)}'`;
536
+ }
537
+ if (/^[A-Za-z0-9@/._-]+$/u.test(text)) return text;
538
+ return `'${text.replace(/'/gu, `'\\''`)}'`;
539
+ }
540
+
541
+ /**
542
+ * A printed command that changes to `dir`, then runs `command` there, so it
543
+ * does the same work pasted from any folder. It runs `command` only when the
544
+ * change worked. For a POSIX shell: `cd <dir> && <command>`. For PowerShell
545
+ * on Windows: `cd -LiteralPath <dir> -ErrorAction Stop; <command>`, because
546
+ * `-LiteralPath` reads `[` and `]` in a folder name literally, and a failed
547
+ * change stops the line in Windows PowerShell 5.1, which has no `&&`, as in
548
+ * PowerShell 7.
549
+ *
550
+ * @param {string} dir an absolute folder
551
+ * @param {string} command the command to run there, its arguments already
552
+ * quoted with {@link quoteCommandArgument}
553
+ * @param {string} [platform] the `process.platform` the command is printed for
554
+ * @returns {string}
555
+ */
556
+ export function commandInFolder(dir, command, platform = process.platform) {
557
+ const folder = quoteCommandArgument(dir, platform);
558
+ return platform === 'win32'
559
+ ? `cd -LiteralPath ${folder} -ErrorAction Stop; ${command}`
560
+ : `cd ${folder} && ${command}`;
561
+ }
@@ -1,6 +1,7 @@
1
1
  // Copyright (c) Meta Platforms, Inc. and affiliates.
2
2
 
3
3
  import {describe, it, expect, afterEach, vi} from 'vitest';
4
+ import {spawnSync} from 'node:child_process';
4
5
  import * as fs from 'node:fs';
5
6
  import * as path from 'node:path';
6
7
  import * as os from 'node:os';
@@ -12,11 +13,32 @@ import {
12
13
  cliBinResolves,
13
14
  getCliInvocation,
14
15
  formatCliCommand,
16
+ quoteCommandArgument,
17
+ commandInFolder,
15
18
  } from './package-manager.mjs';
16
19
 
17
20
  let tmpDir;
18
21
  const ORIGINAL_ARGV1 = process.argv[1];
19
22
 
23
+ /** Prints, as JSON, the folder a command ran in and the arguments it got. */
24
+ const PRINT_RUN =
25
+ 'process.stdout.write(JSON.stringify({cwd: process.cwd(), argv: process.argv.slice(1)}))';
26
+
27
+ /** PowerShell, when it is on the PATH: printed commands target it on Windows. */
28
+ const PWSH = (process.env.PATH ?? '')
29
+ .split(path.delimiter)
30
+ .flatMap(dir => ['pwsh', 'pwsh.exe'].map(name => path.join(dir, name)))
31
+ .find(file => isFile(file));
32
+
33
+ /** @param {string} file */
34
+ function isFile(file) {
35
+ try {
36
+ return fs.statSync(file).isFile();
37
+ } catch {
38
+ return false;
39
+ }
40
+ }
41
+
20
42
  afterEach(() => {
21
43
  if (tmpDir) {
22
44
  fs.rmSync(tmpDir, {recursive: true, force: true});
@@ -48,7 +70,8 @@ const YARN_BERRY_LOCK =
48
70
  '# This file is generated by running "yarn install" inside your project.\n# Manual changes might be lost - proceed with caution!\n\n__metadata:\n version: 8\n';
49
71
 
50
72
  /** An installed CLI's entry, outside any runner cache (a global or workspace install). */
51
- const INSTALLED_ENTRY = '/usr/local/lib/node_modules/@astryxdesign/cli/clients/cli/bin/astryx.mjs';
73
+ const INSTALLED_ENTRY =
74
+ '/usr/local/lib/node_modules/@astryxdesign/cli/clients/cli/bin/astryx.mjs';
52
75
 
53
76
  describe('detectPackageManager', () => {
54
77
  it('detects yarn from yarn.lock', () => {
@@ -132,7 +155,10 @@ describe('detectPackageManager', () => {
132
155
  const dir = makeTmpDir();
133
156
  fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
134
157
  fs.writeFileSync(path.join(dir, 'yarn.lock'), '');
135
- fs.writeFileSync(path.join(dir, '.yarnrc.yml'), 'nodeLinker: node-modules\n');
158
+ fs.writeFileSync(
159
+ path.join(dir, '.yarnrc.yml'),
160
+ 'nodeLinker: node-modules\n',
161
+ );
136
162
  expect(detectPackageManager(dir)).toBe('yarn');
137
163
  });
138
164
 
@@ -425,12 +451,14 @@ describe('isCliOneOff', () => {
425
451
  });
426
452
 
427
453
  it('detects a pnpm dlx cache entry', () => {
428
- process.argv[1] = '/home/u/.cache/pnpm/dlx/9f/node_modules/@astryxdesign/cli/bin/astryx.mjs';
454
+ process.argv[1] =
455
+ '/home/u/.cache/pnpm/dlx/9f/node_modules/@astryxdesign/cli/bin/astryx.mjs';
429
456
  expect(isCliOneOff()).toBe(true);
430
457
  });
431
458
 
432
459
  it('detects a bunx cache entry', () => {
433
- process.argv[1] = '/home/u/.bun/install/cache/@astryxdesign/cli/bin/astryx.mjs';
460
+ process.argv[1] =
461
+ '/home/u/.bun/install/cache/@astryxdesign/cli/bin/astryx.mjs';
434
462
  expect(isCliOneOff()).toBe(true);
435
463
  });
436
464
 
@@ -538,7 +566,8 @@ describe('getCliInvocation', () => {
538
566
  });
539
567
 
540
568
  it('pairs the dlx runner with the scoped package for pnpm one-off', () => {
541
- process.argv[1] = '/home/u/.cache/pnpm/dlx/9f/node_modules/@astryxdesign/cli/bin/astryx.mjs';
569
+ process.argv[1] =
570
+ '/home/u/.cache/pnpm/dlx/9f/node_modules/@astryxdesign/cli/bin/astryx.mjs';
542
571
  const dir = makeTmpDir();
543
572
  fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
544
573
  expect(getCliInvocation(dir)).toBe('pnpm dlx @astryxdesign/cli');
@@ -551,7 +580,9 @@ describe('formatCliCommand', () => {
551
580
  const dir = makeTmpDir();
552
581
  fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
553
582
  linkCliBin(dir);
554
- expect(formatCliCommand('astryx component Button', dir)).toBe('pnpm exec astryx component Button');
583
+ expect(formatCliCommand('astryx component Button', dir)).toBe(
584
+ 'pnpm exec astryx component Button',
585
+ );
555
586
  });
556
587
 
557
588
  it('accepts a bare subcommand (no leading astryx)', () => {
@@ -566,6 +597,162 @@ describe('formatCliCommand', () => {
566
597
  process.argv[1] = '/home/u/.npm/_npx/a1b2/node_modules/.bin/astryx';
567
598
  const dir = makeTmpDir();
568
599
  fs.writeFileSync(path.join(dir, 'package-lock.json'), '{}');
569
- expect(formatCliCommand('astryx component Button', dir)).toBe('npx @astryxdesign/cli component Button');
600
+ expect(formatCliCommand('astryx component Button', dir)).toBe(
601
+ 'npx @astryxdesign/cli component Button',
602
+ );
603
+ });
604
+ });
605
+
606
+ describe('quoteCommandArgument', () => {
607
+ it('leaves a plain value bare', () => {
608
+ for (const platform of ['linux', 'darwin', 'win32']) {
609
+ expect(quoteCommandArgument('0.7.1', platform)).toBe('0.7.1');
610
+ expect(quoteCommandArgument('@acme/widgets', platform)).toBe(
611
+ '@acme/widgets',
612
+ );
613
+ expect(quoteCommandArgument('/home/me/app/src', platform)).toBe(
614
+ '/home/me/app/src',
615
+ );
616
+ }
617
+ });
618
+
619
+ it('single-quotes for a POSIX shell, so $, backticks and double quotes stay literal', () => {
620
+ expect(quoteCommandArgument('/tmp/my app/src', 'linux')).toBe(
621
+ "'/tmp/my app/src'",
622
+ );
623
+ expect(quoteCommandArgument('/tmp/cost $5/src', 'darwin')).toBe(
624
+ "'/tmp/cost $5/src'",
625
+ );
626
+ expect(quoteCommandArgument('a`id`"b"!', 'linux')).toBe('\'a`id`"b"!\'');
627
+ expect(quoteCommandArgument("it's", 'linux')).toBe("'it'\\''s'");
628
+ expect(quoteCommandArgument('C:\\app', 'linux')).toBe("'C:\\app'");
629
+ expect(quoteCommandArgument('', 'linux')).toBe("''");
630
+ });
631
+
632
+ it('keeps a Windows drive path bare', () => {
633
+ expect(quoteCommandArgument('C:\\Users\\me\\app\\src', 'win32')).toBe(
634
+ 'C:\\Users\\me\\app\\src',
635
+ );
636
+ });
637
+
638
+ // Windows output targets PowerShell, not cmd.exe: PowerShell reads a
639
+ // single-quoted value literally, `$`, backticks, `%` and `!` included.
640
+ it('single-quotes for PowerShell on Windows, doubling an embedded quote', () => {
641
+ expect(quoteCommandArgument('C:\\Users\\Jo Smith\\app\\src', 'win32')).toBe(
642
+ "'C:\\Users\\Jo Smith\\app\\src'",
643
+ );
644
+ expect(quoteCommandArgument('C:\\cost $5 %x% !y\\src', 'win32')).toBe(
645
+ "'C:\\cost $5 %x% !y\\src'",
646
+ );
647
+ expect(quoteCommandArgument('C:\\it\'s `x` "q"', 'win32')).toBe(
648
+ "'C:\\it''s `x` \"q\"'",
649
+ );
650
+ // PowerShell also ends a single-quoted string at ‘ ’ ‚ and ‛.
651
+ expect(
652
+ quoteCommandArgument('C:\\Users\\jo\\OneDrive - Macy’s\\app', 'win32'),
653
+ ).toBe("'C:\\Users\\jo\\OneDrive - Macy’’s\\app'");
654
+ expect(quoteCommandArgument('‘a’ ‚b‛', 'win32')).toBe("'‘‘a’’ ‚‚b‛‛'");
655
+ // A POSIX shell reads them literally inside single quotes.
656
+ expect(quoteCommandArgument('/home/jo/Macy’s app', 'linux')).toBe(
657
+ "'/home/jo/Macy’s app'",
658
+ );
659
+ });
660
+ });
661
+
662
+ describe('commandInFolder', () => {
663
+ it('enters the folder, then runs the command only if that worked, in a POSIX shell', () => {
664
+ expect(commandInFolder('/tmp/my app', 'npx x', 'linux')).toBe(
665
+ "cd '/tmp/my app' && npx x",
666
+ );
667
+ expect(commandInFolder('/srv/app', 'npx x', 'darwin')).toBe(
668
+ 'cd /srv/app && npx x',
669
+ );
670
+ });
671
+
672
+ it('enters the folder literally and stops if it cannot, in PowerShell', () => {
673
+ expect(commandInFolder('C:\\a[1] b', 'npx x', 'win32')).toBe(
674
+ "cd -LiteralPath 'C:\\a[1] b' -ErrorAction Stop; npx x",
675
+ );
676
+ });
677
+
678
+ it.skipIf(process.platform === 'win32')(
679
+ 'runs in the folder with every argument unchanged, pasted into /bin/sh elsewhere',
680
+ () => {
681
+ const root = makeTmpDir();
682
+ const project = path.join(root, 'it\'s Macy’s ‘q’ $5 %x% !y `z` "q" [1]');
683
+ fs.mkdirSync(project);
684
+ const args = [path.join(project, 'src'), 'a$b c', "it's", '@scope/pkg@1'];
685
+ const command = commandInFolder(
686
+ project,
687
+ ['npx', ...args.map(arg => quoteCommandArgument(arg, 'linux'))].join(
688
+ ' ',
689
+ ),
690
+ 'linux',
691
+ );
692
+ const ran = spawnSync(
693
+ '/bin/sh',
694
+ [
695
+ '-c',
696
+ `npx() { "$0" -e '${PRINT_RUN}' -- "$@"; }; ${command}`,
697
+ process.execPath,
698
+ ],
699
+ {cwd: root, encoding: 'utf8'},
700
+ );
701
+
702
+ expect(ran.status, ran.stderr).toBe(0);
703
+ expect(JSON.parse(ran.stdout)).toEqual({
704
+ cwd: fs.realpathSync(project),
705
+ argv: args,
706
+ });
707
+ },
708
+ );
709
+
710
+ describe.runIf(PWSH)('in PowerShell, where it is installed', () => {
711
+ it('runs in the folder with every argument unchanged', () => {
712
+ const root = makeTmpDir();
713
+ const project = path.join(root, 'it\'s Macy’s ‘q’ $5 %x% !y `z` "q" [1]');
714
+ fs.mkdirSync(project);
715
+ const args = [path.join(project, 'src'), 'a$b c', "it's", '@scope/pkg@1'];
716
+ const command = commandInFolder(
717
+ project,
718
+ ['npx', ...args.map(arg => quoteCommandArgument(arg, 'win32'))].join(
719
+ ' ',
720
+ ),
721
+ 'win32',
722
+ );
723
+ const npx = `function npx { & ${quoteCommandArgument(process.execPath, 'win32')} -e '${PRINT_RUN}' -- @args }`;
724
+ const ran = spawnSync(
725
+ /** @type {string} */ (PWSH),
726
+ ['-NoProfile', '-NonInteractive', '-Command', `${npx}; ${command}`],
727
+ {cwd: root, encoding: 'utf8'},
728
+ );
729
+
730
+ expect(ran.status, ran.stderr).toBe(0);
731
+ expect(JSON.parse(ran.stdout)).toEqual({
732
+ cwd: fs.realpathSync(project),
733
+ argv: args,
734
+ });
735
+ });
736
+
737
+ it('stops when the folder cannot be entered', () => {
738
+ const root = makeTmpDir();
739
+ const command = commandInFolder(
740
+ path.join(root, 'missing'),
741
+ 'npx',
742
+ 'win32',
743
+ );
744
+ const ran = spawnSync(
745
+ /** @type {string} */ (PWSH),
746
+ [
747
+ '-NoProfile',
748
+ '-NonInteractive',
749
+ '-Command',
750
+ `function npx { 'RAN' }; ${command}`,
751
+ ],
752
+ {cwd: root, encoding: 'utf8'},
753
+ );
754
+
755
+ expect(ran.stdout).not.toContain('RAN');
756
+ });
570
757
  });
571
758
  });
@@ -21,7 +21,8 @@ export function importUserModule(file: string, { fresh }?: {
21
21
  /**
22
22
  * Load a generated theme artifact and its extensionless JS/JSX/TS/TSX graph.
23
23
  * Package specifiers resolve from the consumer project, while relative paths
24
- * resolve from that same project root.
24
+ * resolve from that same project root. An import of an existing `.css` file
25
+ * loads as an empty module.
25
26
  * @param {string} specifier
26
27
  * @param {string} cwd
27
28
  * @returns {Promise<Record<string, unknown>>}
@@ -7,9 +7,11 @@
7
7
  * user-authored module (`.ts` via jiti, `.mjs`/`.js` via native dynamic
8
8
  * import) and (b) find conventional files by basename in a fixed
9
9
  * load-precedence order. Generated theme artifacts also use a dedicated jiti
10
- * path that resolves extensionless JSX/TSX registry imports. These helpers
11
- * centralize that behavior so callers stay in lockstep. A module's stdout writes go to stderr while it loads, so
12
- * project code that prints cannot corrupt a `--json` envelope.
10
+ * path that resolves extensionless JSX/TSX registry imports and loads the
11
+ * stylesheets they import as empty modules. These helpers centralize that
12
+ * behavior so callers stay in lockstep. A module's stdout writes go to stderr
13
+ * while it loads, so project code that prints cannot corrupt a `--json`
14
+ * envelope.
13
15
  *
14
16
  * `loadModuleWithParser` builds on these primitives to provide the single
15
17
  * load/validation boundary shared by config, integration, codemod, and
@@ -125,6 +127,56 @@ const THEME_ARTIFACT_EXTENSIONS = [
125
127
  '.cts',
126
128
  ];
127
129
 
130
+ /**
131
+ * @param {string | symbol} specifier
132
+ * @returns {specifier is string}
133
+ */
134
+ function isStylesheetSpecifier(specifier) {
135
+ return typeof specifier === 'string' && specifier.endsWith('.css');
136
+ }
137
+
138
+ /**
139
+ * Whether `specifier`, resolved from the module at `from`, names an existing
140
+ * `.css` file.
141
+ * @param {string} specifier
142
+ * @param {string} from
143
+ */
144
+ function resolvesToStylesheet(specifier, from) {
145
+ try {
146
+ return createRequire(from).resolve(specifier).endsWith('.css');
147
+ } catch {
148
+ return false;
149
+ }
150
+ }
151
+
152
+ /**
153
+ * A built theme module may import a stylesheet so that the app's bundler emits
154
+ * it. Node cannot load a stylesheet, so an import that ends in `.css` and
155
+ * resolves from the theme module to an existing `.css` file loads as an empty
156
+ * module. Any other import loads as before: a missing stylesheet fails like
157
+ * any missing import, and `./tokens.css` loads `tokens.css.js` when that is
158
+ * the file it names. jiti shows only the import text, so the check resolves it
159
+ * from the theme module's folder, not from the importing module's. A module in
160
+ * another folder fails on a stylesheet it reaches by a different relative
161
+ * path, and passes on a missing stylesheet whose path exists from the theme
162
+ * module's folder.
163
+ * @param {() => string} themeModule returns the theme module's path
164
+ * @returns {Record<string, unknown>}
165
+ */
166
+ function themeArtifactStylesheets(themeModule) {
167
+ return new Proxy(
168
+ {},
169
+ {
170
+ has: (_target, specifier) =>
171
+ specifier !== themeModule() &&
172
+ isStylesheetSpecifier(specifier) &&
173
+ resolvesToStylesheet(specifier, themeModule()),
174
+ get: (_target, specifier) =>
175
+ isStylesheetSpecifier(specifier) ? {} : undefined,
176
+ },
177
+ );
178
+ }
179
+
128
180
  class ThemeArtifactNotFoundError extends Error {
129
181
  code = 'ERR_THEME_ARTIFACT_NOT_FOUND';
130
182
 
@@ -153,17 +205,20 @@ function isMissingPackageExport(error) {
153
205
  /**
154
206
  * Load a generated theme artifact and its extensionless JS/JSX/TS/TSX graph.
155
207
  * Package specifiers resolve from the consumer project, while relative paths
156
- * resolve from that same project root.
208
+ * resolve from that same project root. An import of an existing `.css` file
209
+ * loads as an empty module.
157
210
  * @param {string} specifier
158
211
  * @param {string} cwd
159
212
  * @returns {Promise<Record<string, unknown>>}
160
213
  */
161
214
  export async function importThemeArtifact(specifier, cwd) {
215
+ let themeModule = path.join(cwd, 'package.json');
162
216
  const loader = createJiti(path.join(cwd, 'package.json'), {
163
217
  moduleCache: false,
164
218
  jsx: true,
165
219
  interopDefault: true,
166
220
  extensions: THEME_ARTIFACT_EXTENSIONS,
221
+ virtualModules: themeArtifactStylesheets(() => themeModule),
167
222
  });
168
223
  let target;
169
224
  if (specifier.startsWith('.') || path.isAbsolute(specifier)) {
@@ -179,6 +234,7 @@ export async function importThemeArtifact(specifier, cwd) {
179
234
  if (!fs.existsSync(target)) {
180
235
  throw new ThemeArtifactNotFoundError(specifier);
181
236
  }
237
+ themeModule = target;
182
238
  return await withStdoutOnStderr(() => loader.import(target));
183
239
  }
184
240