@astryxdesign/cli 0.7.5-canary.ae842c8 → 0.7.5-canary.b7ea471

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 (67) hide show
  1. package/README.md +1 -1
  2. package/api/component/_adapter.mjs +16 -1
  3. package/api/component/component.test.mjs +31 -0
  4. package/api/docs/_adapter.d.mts +5 -2
  5. package/api/docs/_adapter.mjs +24 -16
  6. package/api/docs/docs.test.mjs +18 -0
  7. package/api/docs/integrationDocs.test.mjs +2 -2
  8. package/api/integration/pack-check.lifecycle-output.test.mjs +24 -1
  9. package/api/integration/pack-check.mjs +10 -4
  10. package/api/integration/pack-check.test.mjs +5 -1
  11. package/api/search/_adapter.test.mjs +21 -2
  12. package/api/template/template.mjs +3 -1
  13. package/api/template/unknown-name.test.mjs +63 -0
  14. package/api/upgrade/_adapter.d.mts +2 -0
  15. package/api/upgrade/run/failure-receipt.test.mjs +212 -0
  16. package/api/upgrade/run/run.mjs +251 -10
  17. package/api/upgrade/upgrade.doc.mjs +4 -4
  18. package/api/upgrade/upgrade.mjs +19 -4
  19. package/api/upgrade/upgrade.type.d.mts +12 -1
  20. package/api/upgrade/upgrade.type.mjs +17 -4
  21. package/assets/codemods/__tests__/runner.symlinks.test.mjs +205 -0
  22. package/assets/codemods/__tests__/runner.unparseable.test.mjs +457 -0
  23. package/assets/codemods/integration-runner.mjs +8 -2
  24. package/assets/codemods/integration-runner.protection.test.mjs +53 -0
  25. package/assets/codemods/parse.mjs +94 -0
  26. package/assets/codemods/run-codemod.mjs +109 -5
  27. package/assets/codemods/runner.mjs +108 -10
  28. package/assets/codemods/transform-prop.mjs +99 -49
  29. package/assets/codemods/transform-prop.test.mjs +36 -1
  30. package/assets/codemods/transforms/v0.1.3/__tests__/migrate-layout-components-to-experimental.test.mjs +216 -2
  31. package/assets/codemods/transforms/v0.1.3/migrate-layout-components-to-experimental.mjs +88 -6
  32. package/assets/codemods/transforms/v0.6.0/migrate-astryx-theme-selectors-to-data-attrs.mjs +4 -3
  33. package/assets/codemods/transforms/v0.7.0/__tests__/migrate-deprecated-theme-surface.test.mjs +207 -6
  34. package/assets/codemods/transforms/v0.7.0/__tests__/validate-data-token-ownership.test.mjs +123 -70
  35. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface-v0.6-data.mjs +6 -1
  36. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface.mjs +244 -42
  37. package/assets/codemods/transforms/v0.7.0/validate-data-token-ownership.mjs +19 -77
  38. package/assets/docs/tree/styling-advanced.doc.mjs +1 -1
  39. package/assets/templates/blocks/components/CodeBlock/CodeBlockBashCommand.doc.mjs +1 -1
  40. package/assets/templates/blocks/components/CodeBlock/CodeBlockBashCommand.tsx +10 -2
  41. package/assets/templates/pages/library/page.tsx +1 -2
  42. package/authoring/codemod/type.ts +10 -0
  43. package/clients/cli/commands/upgrade.doc.mjs +27 -0
  44. package/clients/cli/commands/upgrade.file-protection.test.mjs +175 -0
  45. package/clients/cli/commands/upgrade.flag-help.test.mjs +37 -0
  46. package/clients/cli/commands/upgrade.integration-policy.test.mjs +103 -0
  47. package/clients/cli/commands/upgrade.mjs +9 -2
  48. package/foundation/doc-compiler/doc-loads.test.mjs +5 -5
  49. package/foundation/doc-compiler/import.mjs +81 -8
  50. package/foundation/doc-compiler/read.d.mts +4 -3
  51. package/foundation/doc-compiler/read.mjs +15 -10
  52. package/foundation/doc-compiler/read.test.mjs +59 -1
  53. package/foundation/fs/module-loader.d.mts +3 -2
  54. package/foundation/fs/module-loader.mjs +3 -2
  55. package/foundation/fs/publish-file-eperm-mutation.test.mjs +2 -0
  56. package/foundation/fs/read-record.d.mts +27 -0
  57. package/foundation/fs/read-record.mjs +83 -15
  58. package/foundation/fs/read-record.test.mjs +88 -1
  59. package/foundation/response/base.d.ts +7 -0
  60. package/foundation/response/error-codes.doc.mjs +3 -2
  61. package/foundation/response/error-codes.mjs +1 -1
  62. package/foundation/response/json.d.mts +10 -3
  63. package/foundation/response/json.mjs +16 -4
  64. package/foundation/text/suggest-order.d.mts +17 -3
  65. package/foundation/text/suggest-order.mjs +58 -13
  66. package/foundation/text/suggest-order.test.mjs +53 -0
  67. package/package.json +10 -9
package/README.md CHANGED
@@ -209,7 +209,7 @@ if (isError(result)) {
209
209
  | `ERR_UNKNOWN_AGENT` | An unrecognized `--agent` value was passed to init. |
210
210
  | `ERR_UNKNOWN_FEATURE` | An unrecognized `--features` value was passed to init. |
211
211
  | `ERR_UNKNOWN_CODEMOD` | A `--codemod` value did not match any registered codemod (upgrade). |
212
- | `ERR_CODEMOD_FAILED` | One or more codemods failed during an upgrade run. |
212
+ | `ERR_CODEMOD_FAILED` | A codemod or post-codemod hook failed during an upgrade run; the error carries a `receipt` that lists the files the run already changed. |
213
213
  | `ERR_CODEMOD_PROTECTED` | A required codemod change remains blocked by a protected consumer file. |
214
214
  | `ERR_CODEMOD_PROTECTION_SOURCE` | A working-tree protection declaration could not be read or parsed. |
215
215
  | `ERR_NOT_FOUND` | A generic discover/lookup query matched nothing in any package. |
@@ -49,12 +49,16 @@ import {
49
49
  synonymMatches,
50
50
  } from '../../foundation/text/suggest-order.mjs';
51
51
  import {AstryxError, coreDirOrThrow} from '../error.mjs';
52
+ import {levenshteinDistance} from '../../foundation/text/levenshtein.mjs';
52
53
  import {
53
54
  componentLinkProvider,
54
55
  linkComponentDoc,
55
56
  loadDocsCatalog,
56
57
  } from '../docs/_adapter.mjs';
57
58
 
59
+ /** How far below the first suggestion's score a later one may be. */
60
+ const NEAR_FIRST = 10;
61
+
58
62
  /** @type {Record<string, {synonyms?: string[]}> | undefined} */
59
63
  let cards;
60
64
  /**
@@ -503,9 +507,20 @@ export async function resolveUnscopedDoc(dirName, {coreDir, cwd, name}) {
503
507
  Object.values(components).flat(),
504
508
  synonymMatches(dirName, searchCards()),
505
509
  ).slice(0, count);
510
+ // Past the first two suggestions, only the ones about as close as
511
+ // the first (within NEAR_FIRST points), or a close spelling of the
512
+ // whole typed name (a typo): a weaker match after a strong one reads
513
+ // as noise. The list only gets shorter and keeps at least two.
514
+ const typed = dirName.toLowerCase();
515
+ const nearFirst = candidates.filter(
516
+ (c, i) =>
517
+ i < 2 ||
518
+ c.score >= candidates[0].score - NEAR_FIRST ||
519
+ levenshteinDistance(c.name.toLowerCase(), typed) <= 2,
520
+ );
506
521
  throw new AstryxError(
507
522
  `No component named "${name}"`,
508
- candidates.map(c => ({name: c.name, reason: c.reason})),
523
+ nearFirst.map(c => ({name: c.name, reason: c.reason})),
509
524
  ERROR_CODES.ERR_UNKNOWN_COMPONENT,
510
525
  );
511
526
  }
@@ -499,3 +499,34 @@ describe('component dispatcher — detail levels on single component (text only)
499
499
  SLOW,
500
500
  );
501
501
  });
502
+
503
+ describe('component not-found suggestions', () => {
504
+ const suggested = async (/** @type {string} */ name) => {
505
+ const error = await component(name, {cwd}).catch(e => e);
506
+ expect(error).toBeInstanceOf(AstryxError);
507
+ expect(error.code).toBe('ERR_UNKNOWN_COMPONENT');
508
+ return error.suggestions.map((/** @type {{name: string}} */ s) => s.name);
509
+ };
510
+
511
+ it(
512
+ 'leaves out a weaker match after a strong first suggestion',
513
+ async () => {
514
+ // FieldLabel is another name for it; past the second suggestion, the
515
+ // matches on one word of the name ("input", "label") are weaker and add
516
+ // only noise.
517
+ const names = await suggested('InputLabel');
518
+ expect(names[0]).toBe('FieldLabel');
519
+ expect(names).toHaveLength(2);
520
+ },
521
+ SLOW,
522
+ );
523
+
524
+ it(
525
+ 'keeps a close spelling of the whole name after a stronger first match',
526
+ async () => {
527
+ expect(await suggested('Blockqoute')).toContain('Blockquote');
528
+ expect(await suggested('TextrAea')).toContain('TextArea');
529
+ },
530
+ SLOW,
531
+ );
532
+ });
@@ -335,8 +335,11 @@ export function holdsOwnName(tree: DocsTree, catalog: DocsCatalog, entry: import
335
335
  export function routeOwner(tree: DocsTree, entry: import("../../foundation/discovery/docs-discovery.mjs").DocsTopicEntry): TreeNode | null;
336
336
  /**
337
337
  * The error for a docs argument that names nothing. For a route, it suggests
338
- * the children of the deepest namespace the route reaches; otherwise, every
339
- * topic and every top-level namespace.
338
+ * every child of the deepest namespace the route reaches, closest first.
339
+ * Otherwise it suggests the docs the argument names in another spelling, or
340
+ * failing that the topics and top-level namespaces, closest first and cut
341
+ * where the matches get weaker (every one of them when none shares a word
342
+ * with the argument).
340
343
  * @param {unknown} topic
341
344
  * @param {DocsCatalog} catalog
342
345
  * @returns {Promise<AstryxError>}
@@ -77,6 +77,7 @@ import {
77
77
  discoverIntegrationTemplatesForOne,
78
78
  } from '../../foundation/discovery/template-adapter.mjs';
79
79
  import {findCoreDir} from '../../foundation/fs/paths.mjs';
80
+ import {reusedWhileUnchanged} from '../../foundation/fs/read-record.mjs';
80
81
  import {AstryxError} from '../error.mjs';
81
82
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
82
83
  import {orderRouteSuggestions} from '../../foundation/text/suggest-order.mjs';
@@ -393,8 +394,8 @@ export function projectTree(catalog, {fresh = false} = {}) {
393
394
  return tree;
394
395
  }
395
396
 
396
- /** @type {ReturnType<typeof loadTreeInputs> | undefined} */
397
- let cliTreeInputs;
397
+ /** The CLI's own tree files, loaded again after one of them changes. */
398
+ const cliTreeInputs = reusedWhileUnchanged(() => loadTreeInputs());
398
399
 
399
400
  /**
400
401
  * Every flat topic in the catalog, as the tree's topic levels read it.
@@ -441,8 +442,7 @@ async function flatTopicInputs(catalog) {
441
442
  */
442
443
  async function buildProjectTree(catalog, fresh) {
443
444
  const added = catalog.treeInputs;
444
- if (fresh || !cliTreeInputs) cliTreeInputs = loadTreeInputs();
445
- const cli = await cliTreeInputs;
445
+ const cli = await cliTreeInputs({fresh});
446
446
  const result = buildDocsTree({
447
447
  namespaces: [...cli.namespaces, ...added.flatMap(each => each.namespaces)],
448
448
  docs: [...cli.docs, ...added.flatMap(each => each.guides)],
@@ -573,11 +573,15 @@ function identitiesOf(tree) {
573
573
  /**
574
574
  * The CLI's authoring docs, by kind and name. The field reference under
575
575
  * `astryx docs authoring` reads each as one section keyed by its name, so a
576
- * link to one opens that section. Loaded once per process, like the CLI's
577
- * tree files.
578
- * @type {Promise<Map<string, any>> | undefined}
576
+ * link to one opens that section. Loaded again after one of them changes,
577
+ * like the CLI's tree files.
579
578
  */
580
- let authoringDocs;
579
+ const authoringDocs = reusedWhileUnchanged(() =>
580
+ loadAuthoringSelfDocs().then(
581
+ ({loaded}) =>
582
+ new Map(loaded.map(({doc}) => [`${doc.type}\u0000${doc.name}`, doc])),
583
+ ),
584
+ );
581
585
 
582
586
  /**
583
587
  * The CLI authoring doc a link names. The `authoring` namespace is the CLI's
@@ -587,11 +591,7 @@ let authoringDocs;
587
591
  * @returns {Promise<any | null>}
588
592
  */
589
593
  async function authoringDoc(kind, name) {
590
- authoringDocs ??= loadAuthoringSelfDocs().then(
591
- ({loaded}) =>
592
- new Map(loaded.map(({doc}) => [`${doc.type}\u0000${doc.name}`, doc])),
593
- );
594
- return (await authoringDocs).get(`${kind}\u0000${name}`) ?? null;
594
+ return (await authoringDocs()).get(`${kind}\u0000${name}`) ?? null;
595
595
  }
596
596
 
597
597
  /**
@@ -1844,8 +1844,11 @@ function movedRoute(topic, tree) {
1844
1844
 
1845
1845
  /**
1846
1846
  * The error for a docs argument that names nothing. For a route, it suggests
1847
- * the children of the deepest namespace the route reaches; otherwise, every
1848
- * topic and every top-level namespace.
1847
+ * every child of the deepest namespace the route reaches, closest first.
1848
+ * Otherwise it suggests the docs the argument names in another spelling, or
1849
+ * failing that the topics and top-level namespaces, closest first and cut
1850
+ * where the matches get weaker (every one of them when none shares a word
1851
+ * with the argument).
1849
1852
  * @param {unknown} topic
1850
1853
  * @param {DocsCatalog} catalog
1851
1854
  * @returns {Promise<AstryxError>}
@@ -1854,6 +1857,8 @@ export async function unknownTopicError(topic, catalog) {
1854
1857
  const tree = await projectTree(catalog);
1855
1858
  /** @type {Array<{name: string, reason: string}>} */
1856
1859
  let suggestions = [];
1860
+ // Route children stay whole (spec:AST-046); only the other lists are cut.
1861
+ let routeChildren = false;
1857
1862
  if (typeof topic === 'string' && topic.includes('/')) {
1858
1863
  const parts = topic.split('/');
1859
1864
  for (
@@ -1863,6 +1868,7 @@ export async function unknownTopicError(topic, catalog) {
1863
1868
  ) {
1864
1869
  const near = tree.get(parts.slice(0, depth).join('/'));
1865
1870
  if (near) {
1871
+ routeChildren = true;
1866
1872
  suggestions = near.slots.flatMap(slot =>
1867
1873
  slot.children.map(route => ({
1868
1874
  name: route,
@@ -1894,7 +1900,9 @@ export async function unknownTopicError(topic, catalog) {
1894
1900
  ];
1895
1901
  }
1896
1902
  if (typeof topic === 'string') {
1897
- suggestions = orderRouteSuggestions(topic, suggestions);
1903
+ suggestions = orderRouteSuggestions(topic, suggestions, {
1904
+ closest: !routeChildren,
1905
+ });
1898
1906
  }
1899
1907
  // A route that moved names where it went, ahead of the usual suggestions
1900
1908
  // (spec:AST-046 FR9, FR6).
@@ -254,6 +254,24 @@ describe('docs() dispatcher routing', () => {
254
254
  );
255
255
  }, SLOW);
256
256
 
257
+ it('an unknown route keeps every child of its namespace, closest first', async () => {
258
+ const error = await docs('tokens/usage').catch(e => e);
259
+ expect(error.code).toBe('ERR_UNKNOWN_TOPIC');
260
+ const names = error.suggestions.map(s => s.name);
261
+ expect(names[0]).toBe('tokens/tokens-usage');
262
+ const none = await docs('tokens/zzzz-nope').catch(e => e);
263
+ expect([...names].sort()).toEqual(none.suggestions.map(s => s.name).sort());
264
+ }, SLOW);
265
+
266
+ it('an unknown flat topic is cut where the matches get weaker', async () => {
267
+ const error = await docs('authoring-at-meta').catch(e => e);
268
+ expect(error.suggestions.map(s => s.name)).toEqual(['authoring']);
269
+ // One-letter words do not narrow it: `a11y` keeps the whole browse list.
270
+ const browse = await docs('zzzz-nope').catch(e => e);
271
+ const a11y = await docs('a11y').catch(e => e);
272
+ expect(a11y.suggestions.length).toBe(browse.suggestions.length);
273
+ }, SLOW);
274
+
257
275
  it('a section no guide of a namespace has -> ERR_UNKNOWN_SECTION, naming its guides', async () => {
258
276
  const err = await docs('cli', 'zzzz-nope').catch(e => e);
259
277
  expect(err).toBeInstanceOf(AstryxError);
@@ -450,11 +450,11 @@ describe('integration-contributed topics', () => {
450
450
 
451
451
  it('offers the contributed topics as suggestions on an unknown one', async () => {
452
452
  scaffold({'deploying.doc.mjs': topic()});
453
- await expect(docs('nope-not-a-topic', undefined, {cwd: tmpDir, full: true})).rejects.toBeInstanceOf(
453
+ await expect(docs('zzqx-qqzz', undefined, {cwd: tmpDir, full: true})).rejects.toBeInstanceOf(
454
454
  AstryxError,
455
455
  );
456
456
  try {
457
- await docs('nope-not-a-topic', undefined, {cwd: tmpDir, full: true});
457
+ await docs('zzqx-qqzz', undefined, {cwd: tmpDir, full: true});
458
458
  } catch (err) {
459
459
  expect(err.suggestions.map(s => s.name)).toContain('deploying');
460
460
  }
@@ -1,6 +1,6 @@
1
1
  // Copyright (c) Meta Platforms, Inc. and affiliates.
2
2
 
3
- import {afterEach, beforeEach, describe, expect, it} from 'vitest';
3
+ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
4
4
  import {spawnSync} from 'node:child_process';
5
5
  import * as fs from 'node:fs';
6
6
  import * as path from 'node:path';
@@ -123,4 +123,27 @@ describe('integrationPackCheck with lifecycle script output', () => {
123
123
  expect(failure?.message).toContain('npm pack failed (exit 3)');
124
124
  expect(failure?.message).toContain('prepack exploded');
125
125
  });
126
+
127
+ it.skipIf(process.platform === 'win32')(
128
+ 'packs with npm itself when an earlier npm on the PATH refuses every command',
129
+ async () => {
130
+ writeThemePackage({});
131
+ const refusing = path.join(tmpDir, '.refusing-bin');
132
+ fs.mkdirSync(refusing);
133
+ fs.writeFileSync(
134
+ path.join(refusing, 'npm'),
135
+ "#!/bin/sh\necho 'npm commands are not allowed on this machine'\nexit 1\n",
136
+ {mode: 0o755},
137
+ );
138
+ vi.stubEnv('PATH', `${refusing}${path.delimiter}${process.env.PATH}`);
139
+ try {
140
+ const result = await integrationPackCheck({cwd: tmpDir});
141
+
142
+ expect(result.data.issues).toEqual([]);
143
+ expect(result.data.packable).toBe(true);
144
+ } finally {
145
+ vi.unstubAllEnvs();
146
+ }
147
+ },
148
+ );
126
149
  });
@@ -25,6 +25,7 @@ import * as os from 'node:os';
25
25
  import {fileURLToPath} from 'node:url';
26
26
  import {spawnSync} from 'node:child_process';
27
27
  import {assertWithin} from '../../foundation/fs/path-safety.mjs';
28
+ import {npmCommand} from '../../foundation/release/cache.mjs';
28
29
  import {commandTokensIn} from '../../foundation/doc-compiler/doc-syntax.mjs';
29
30
  import {resolvePackageDir} from '../../foundation/integrations/integrations.mjs';
30
31
  import {
@@ -265,17 +266,22 @@ function npmPackErrorDetail(output) {
265
266
  /**
266
267
  * Run `npm pack --json` with output directed to `destDir` so no preexisting
267
268
  * tgz is overwritten. This intentionally runs the package lifecycle, matching
268
- * the artifact `npm publish` would produce. Uses spawnSync with an args array —
269
- * no shell — so paths with metacharacters cannot inject.
269
+ * the artifact `npm publish` would produce. npm starts the way the CLI starts
270
+ * it everywhere else (`npmCommand`): npm's own entry file run with this Node
271
+ * when one is found, so an `npm` earlier on the PATH that is not npm itself
272
+ * cannot answer for it. Uses spawnSync with an args array — no shell — so
273
+ * paths with metacharacters cannot inject.
270
274
  *
271
275
  * @param {string} packageDir
272
276
  * @param {string} destDir
273
277
  * @returns {{filename: string, fileCount: number, size: number, unpackedSize: number, packedPaths: Set<string>}}
274
278
  */
275
279
  function runNpmPack(packageDir, destDir) {
280
+ const npm = npmCommand();
276
281
  const result = spawnSync(
277
- 'npm',
282
+ npm.command,
278
283
  [
284
+ ...npm.prefix,
279
285
  'pack',
280
286
  '--json',
281
287
  '--silent',
@@ -284,7 +290,7 @@ function runNpmPack(packageDir, destDir) {
284
290
  '--foreground-scripts=false',
285
291
  `--pack-destination=${destDir}`,
286
292
  ],
287
- {cwd: packageDir, encoding: 'utf-8', timeout: 60_000},
293
+ {cwd: packageDir, encoding: 'utf-8', shell: false, timeout: 60_000},
288
294
  );
289
295
  if (result.error) {
290
296
  throw new Error(`Could not start npm pack: ${result.error.message}`);
@@ -2125,10 +2125,13 @@ describe('integrationPackCheck', () => {
2125
2125
  ).toThrow(/without a files array/);
2126
2126
  });
2127
2127
 
2128
- it('reports npm missing from PATH as pack_failed', async () => {
2128
+ it('reports pack_failed when no npm can be found', async () => {
2129
2129
  writePackage({files: ['astryx.integration.mjs', 'themes']});
2130
2130
  const originalPath = process.env.PATH;
2131
+ const originalExecPath = process.execPath;
2131
2132
  process.env.PATH = '';
2133
+ // A Node with no npm beside it, and no npm on the PATH.
2134
+ process.execPath = path.join(tmpDir, 'no-npm', 'bin', 'node');
2132
2135
  try {
2133
2136
  const result = await integrationPackCheck({cwd: tmpDir});
2134
2137
  expect(result.data.packable).toBe(false);
@@ -2140,6 +2143,7 @@ describe('integrationPackCheck', () => {
2140
2143
  );
2141
2144
  } finally {
2142
2145
  process.env.PATH = originalPath;
2146
+ process.execPath = originalExecPath;
2143
2147
  }
2144
2148
  });
2145
2149
 
@@ -85,7 +85,7 @@ describe('gatherCandidatesReused', () => {
85
85
  );
86
86
 
87
87
  it(
88
- 'gathers again when a file the gather read changes, in a linked package too',
88
+ 'gathers again when a file the gather read or imported changes, in a linked package too',
89
89
  async () => {
90
90
  // A consumer whose integration is a symlink to a package folder
91
91
  // elsewhere, as a workspace package is.
@@ -162,7 +162,26 @@ describe('gatherCandidatesReused', () => {
162
162
  // An edited file the gather read: the linked package's manifest.
163
163
  const later = new Date(Date.now() + 5_000);
164
164
  fs.utimesSync(path.join(pkg, 'package.json'), later, later);
165
- expect(await gatherCandidatesReused(options)).not.toBe(second);
165
+ const third = await gatherCandidatesReused(options);
166
+ expect(third).not.toBe(second);
167
+
168
+ // An edited doc the gather imported: the next gather reads its new
169
+ // content, not the module this process imported first.
170
+ fs.writeFileSync(
171
+ path.join(pkg, 'components', 'FancyGizmo.doc.mjs'),
172
+ `export default {
173
+ type: 'component',
174
+ name: 'FancyGizmo',
175
+ keywords: ['gizmo'],
176
+ usage: {description: 'A shinier part, now with sprockets.'},
177
+ props: [],
178
+ };\n`,
179
+ );
180
+ const fourth = await gatherCandidatesReused(options);
181
+ expect(fourth).not.toBe(third);
182
+ expect(
183
+ JSON.stringify(fourth.all.find(c => c.name === 'FancyGizmo')),
184
+ ).toContain('A shinier part, now with sprockets.');
166
185
  } finally {
167
186
  fs.rmSync(dir, {recursive: true, force: true});
168
187
  fs.rmSync(pkg, {recursive: true, force: true});
@@ -190,7 +190,9 @@ export async function template(name, options = {}) {
190
190
  if (name && candidates.length === 0) {
191
191
  throw new AstryxError(
192
192
  `Unknown template "${name}"`,
193
- orderByAffinity(name, templates, t => [t.dirName, t.name]).map(t => ({
193
+ orderByAffinity(name, templates, t => [t.dirName, t.name], {
194
+ closest: true,
195
+ }).map(t => ({
194
196
  name: t.dirName,
195
197
  reason: `${t.type} template`,
196
198
  })),
@@ -0,0 +1,63 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file The suggestions an unknown template name prints: the closest
5
+ * templates first, and the list stops where the matches get weaker. A name
6
+ * that shares no word with any template still lists every template.
7
+ */
8
+
9
+ import {describe, it, expect} from 'vitest';
10
+ import * as path from 'node:path';
11
+ import {fileURLToPath} from 'node:url';
12
+ import {template} from './template.mjs';
13
+ import {nameWords} from '../../foundation/text/suggest-order.mjs';
14
+
15
+ const cwd = path.resolve(
16
+ path.dirname(fileURLToPath(import.meta.url)),
17
+ '../../../..',
18
+ );
19
+ const SLOW = 30_000;
20
+
21
+ /** @param {string} name */
22
+ async function suggested(name) {
23
+ const error = await template(name, {cwd}).catch(e => e);
24
+ expect(error.code).toBe('ERR_UNKNOWN_TEMPLATE');
25
+ return error.suggestions.map((/** @type {{name: string}} */ s) => s.name);
26
+ }
27
+
28
+ describe('unknown template suggestions', () => {
29
+ it(
30
+ 'lists only templates that carry the typed words when one carries them all',
31
+ async () => {
32
+ const all = await suggested('zzqx-nothing-like-it');
33
+ const near = await suggested('settings-panel');
34
+ expect(near.length).toBeGreaterThan(0);
35
+ expect(near.length).toBeLessThan(all.length);
36
+ for (const name of near.slice(1)) {
37
+ const words = nameWords(name);
38
+ expect(words).toContain('setting');
39
+ expect(words).toContain('panel');
40
+ }
41
+ },
42
+ SLOW,
43
+ );
44
+
45
+ it(
46
+ 'does not narrow the list on a one-letter word',
47
+ async () => {
48
+ const all = await suggested('zzqx-nothing-like-it');
49
+ expect(await suggested('a11y')).toHaveLength(all.length);
50
+ },
51
+ SLOW,
52
+ );
53
+
54
+ it(
55
+ 'lists every template when no template shares a word with the name',
56
+ async () => {
57
+ const all = await suggested('zzqx-nothing-like-it');
58
+ expect(new Set(all).size).toBe(all.length);
59
+ expect(all.length).toBeGreaterThan(100);
60
+ },
61
+ SLOW,
62
+ );
63
+ });
@@ -206,6 +206,7 @@ export function runCoreCodemods(versionManifests: CoreVersionManifest[], { apply
206
206
  writtenFiles: string[];
207
207
  stagedContents: Map<string, string>;
208
208
  protectedFiles: import("../../authoring/codemod/type").CodemodRunResult["protectedFiles"];
209
+ declinedCandidates: NonNullable<import("../../authoring/codemod/type").CodemodRunResult["declinedCandidates"]>;
209
210
  errors: Array<{
210
211
  file: string;
211
212
  codemod: string;
@@ -301,6 +302,7 @@ export function runIntegrationCodemodsStep(versionGroups: Array<{
301
302
  writtenFiles: string[];
302
303
  stagedContents: Map<string, string>;
303
304
  protectedFiles: import("../../authoring/codemod/type").CodemodRunResult["protectedFiles"];
305
+ declinedCandidates: NonNullable<import("../../authoring/codemod/type").CodemodRunResult["declinedCandidates"]>;
304
306
  errors: Array<{
305
307
  file: string;
306
308
  codemod: string;