@astryxdesign/cli 0.6.6-canary.cc0df20 → 0.6.6-canary.cf59be8

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 (31) hide show
  1. package/api/component/component-replacement.test.mjs +12 -0
  2. package/api/component/component.doc.mjs +5 -2
  3. package/api/docs/detail/section/section.d.mts +44 -0
  4. package/api/docs/detail/section/section.mjs +164 -13
  5. package/api/docs/docs.doc.mjs +2 -2
  6. package/api/docs/docs.mjs +11 -16
  7. package/api/docs/docs.test.mjs +7 -8
  8. package/api/docs/namespace-section.test.mjs +260 -0
  9. package/api/doctor/doctor.d.mts +6 -0
  10. package/api/doctor/doctor.mjs +149 -40
  11. package/api/doctor/doctor.test.mjs +104 -0
  12. package/api/gap-report/gap-report.doc.mjs +2 -1
  13. package/api/integration/validate-integration.mjs +20 -4
  14. package/api/integration/validate-integration.test.mjs +73 -0
  15. package/api/search/search.d.mts +44 -0
  16. package/api/search/search.domain-priority.test.mjs +261 -0
  17. package/api/search/search.mjs +191 -29
  18. package/api/swizzle/swizzle.doc.mjs +5 -2
  19. package/clients/cli/commands/component/index.mjs +4 -1
  20. package/clients/cli/commands/component-replacement.text.test.mjs +45 -0
  21. package/clients/cli/commands/docs.doc.mjs +2 -1
  22. package/clients/cli/commands/docs.test.mjs +12 -9
  23. package/clients/cli/commands/doctor-integration-components.doc.mjs +1 -1
  24. package/clients/cli/commands/doctor.test.mjs +33 -0
  25. package/clients/cli/lib/component-format.mjs +13 -3
  26. package/foundation/env/package-manager.d.mts +3 -0
  27. package/foundation/env/package-manager.mjs +71 -3
  28. package/foundation/env/package-manager.test.mjs +82 -1
  29. package/foundation/integrations/validate-contributions.d.mts +16 -0
  30. package/foundation/integrations/validate-contributions.mjs +56 -8
  31. package/package.json +9 -9
@@ -24,6 +24,7 @@ import * as fs from 'node:fs';
24
24
  import * as path from 'node:path';
25
25
 
26
26
  import {MIN_NODE_VERSION, isNodeVersionSupported} from '../../foundation/env/node-version.mjs';
27
+ import {AGENT_DOC_PATHS} from '../../foundation/agent-docs/agent-doc-state.mjs';
27
28
  import {CLI_ROOT, findCoreDir, findInstalledPackage} from '../../foundation/fs/paths.mjs';
28
29
  import {explainPackageManager, getCliInvocation} from '../../foundation/env/package-manager.mjs';
29
30
  import {
@@ -85,6 +86,9 @@ import {checkAppThemes, checkThemes} from './theme-checks.mjs';
85
86
  * Combined project-level integration issues, including cross-package template replacement warnings.
86
87
  * @property {Error|null} [configError] - Error thrown while resolving the config
87
88
  * path (e.g. multiple config files present), surfaced by checkConfig as a FAIL.
89
+ * @property {string|null} [projectError] - Why the CLI could not load the
90
+ * project from its config, when it could not. Checks that need the loaded
91
+ * project quote it when they skip, so a skip says what was found.
88
92
  */
89
93
 
90
94
  /* ── helpers ──────────────────────────────────────────────────────────── */
@@ -113,6 +117,64 @@ function pkgVersion(dir) {
113
117
  return pkg?.version ?? null;
114
118
  }
115
119
 
120
+ /**
121
+ * The first line of an error message, bounded for a one-line check message.
122
+ * @param {string} message
123
+ * @returns {string}
124
+ */
125
+ function firstLine(message) {
126
+ return String(message).split('\n')[0].slice(0, 300);
127
+ }
128
+
129
+ /**
130
+ * The message of a check that needs the loaded project and could not have it.
131
+ * It carries the reason the CLI gave, so the line says what Doctor found
132
+ * instead of only that it did not look.
133
+ * @param {DoctorContext} ctx
134
+ * @param {string} what
135
+ * @returns {string}
136
+ */
137
+ function skippedBecause(ctx, what) {
138
+ return ctx.projectError
139
+ ? `Skipped — ${what}: ${firstLine(ctx.projectError)}`
140
+ : `Skipped — ${what}.`;
141
+ }
142
+
143
+ /** Integrations one message names before it counts the rest. */
144
+ const NAMED_INTEGRATIONS = 10;
145
+
146
+ /**
147
+ * @param {Array<{name?: string, __spec?: string}>} integrations
148
+ * @returns {string}
149
+ */
150
+ function nameIntegrations(integrations) {
151
+ const names = integrations.map(
152
+ integration => integration.name ?? integration.__spec ?? '(integration)',
153
+ );
154
+ return names.length <= NAMED_INTEGRATIONS
155
+ ? names.join(', ')
156
+ : `${names.slice(0, NAMED_INTEGRATIONS).join(', ')} and ${names.length - NAMED_INTEGRATIONS} more`;
157
+ }
158
+
159
+ /**
160
+ * The project's root: the folder of its config, else of the nearest
161
+ * package.json above the working directory (where the config is looked for),
162
+ * else the working directory.
163
+ * @param {DoctorContext} ctx
164
+ * @returns {string}
165
+ */
166
+ function projectRootOf(ctx) {
167
+ if (ctx.configPath) return path.dirname(ctx.configPath);
168
+ let dir = ctx.cwd;
169
+ for (let i = 0; i < 50; i++) {
170
+ if (fs.existsSync(path.join(dir, 'package.json'))) return dir;
171
+ const parent = path.dirname(dir);
172
+ if (parent === dir) break;
173
+ dir = parent;
174
+ }
175
+ return ctx.cwd;
176
+ }
177
+
116
178
  /* ── individual checks ────────────────────────────────────────────────── */
117
179
 
118
180
  /**
@@ -255,6 +317,18 @@ export async function checkConfig(ctx) {
255
317
  fix: 'Export a default object from astryx.config.mjs, e.g. `export default { integrations: [] };`.',
256
318
  };
257
319
  }
320
+ // Importing is not the whole test: the CLI also validates the config, and
321
+ // a config it rejects leaves every project-aware command without the
322
+ // project. That config is not clean, so this warns (exit code unchanged).
323
+ if (ctx.projectError) {
324
+ return {
325
+ id: 'config',
326
+ label: 'astryx.config.mjs',
327
+ status: 'warn',
328
+ message: `astryx.config.mjs loads, but the CLI could not load the project from it: ${firstLine(ctx.projectError)}`,
329
+ fix: 'Fix what the message names. `astryx docs authoring config` lists every field astryx.config accepts.',
330
+ };
331
+ }
258
332
  return {
259
333
  id: 'config',
260
334
  label: 'astryx.config.mjs',
@@ -304,7 +378,7 @@ export function checkImplicitIntegrations(ctx) {
304
378
  id,
305
379
  label,
306
380
  status: 'info',
307
- message: 'Skipped — the project configuration could not be read.',
381
+ message: skippedBecause(ctx, 'the project configuration could not be read'),
308
382
  };
309
383
  }
310
384
 
@@ -407,27 +481,30 @@ function describeUnreadableManifests(failures) {
407
481
  * @returns {DoctorCheck}
408
482
  */
409
483
  export function checkAgentDocs(ctx) {
410
- const candidates = [
411
- 'AGENTS.md',
412
- 'CLAUDE.md',
413
- path.join('.claude', 'CLAUDE.md'),
414
- '.cursorrules',
415
- ];
416
- const present = candidates.filter(rel => fs.existsSync(path.join(ctx.cwd, rel)));
484
+ // Every file init can write (one shared list), looked for in the working
485
+ // directory and in the project root: run from src/, the docs sit at the root.
486
+ const dirs = [...new Set([ctx.cwd, projectRootOf(ctx)])];
487
+ const present = dirs.flatMap(dir =>
488
+ AGENT_DOC_PATHS.map(rel => path.join(dir, rel)).filter(abs =>
489
+ fs.existsSync(abs),
490
+ ),
491
+ );
492
+ /** @param {string} abs */
493
+ const shown = abs => path.relative(ctx.cwd, abs) || path.basename(abs);
417
494
 
418
495
  if (present.length === 0) {
419
496
  return {
420
497
  id: 'agent-docs',
421
498
  label: 'AI agent docs',
422
499
  status: 'info',
423
- message: 'No agent docs (CLAUDE.md / AGENTS.md / .cursorrules) found.',
500
+ message: `No agent docs found: looked for ${AGENT_DOC_PATHS.join(', ')} in ${dirs.map(dir => path.relative(ctx.cwd, dir) || '.').join(' and ')}.`,
424
501
  fix: `Generate agent docs with \`${getCliInvocation(ctx.cwd)} init --features agents\`.`,
425
502
  };
426
503
  }
427
504
 
428
- const withMarkers = present.filter(rel => {
505
+ const withMarkers = present.filter(abs => {
429
506
  try {
430
- const content = fs.readFileSync(path.join(ctx.cwd, rel), 'utf-8');
507
+ const content = fs.readFileSync(abs, 'utf-8');
431
508
  return (
432
509
  (content.includes('<!-- ASTRYX:START -->') || content.includes('<!-- XDS:START -->')) &&
433
510
  (content.includes('<!-- ASTRYX:END -->') || content.includes('<!-- XDS:END -->'))
@@ -442,7 +519,7 @@ export function checkAgentDocs(ctx) {
442
519
  id: 'agent-docs',
443
520
  label: 'AI agent docs',
444
521
  status: 'warn',
445
- message: `Agent docs present (${present.join(', ')}) but no Astryx section markers found.`,
522
+ message: `Agent docs present (${present.map(shown).join(', ')}) but no Astryx section markers found.`,
446
523
  fix: `Add the Astryx section to your agent docs with \`${getCliInvocation(ctx.cwd)} init --features agents\`.`,
447
524
  };
448
525
  }
@@ -451,7 +528,7 @@ export function checkAgentDocs(ctx) {
451
528
  id: 'agent-docs',
452
529
  label: 'AI agent docs',
453
530
  status: 'pass',
454
- message: `Astryx agent docs section present in ${withMarkers.join(', ')}.`,
531
+ message: `Astryx agent docs section present in ${withMarkers.map(shown).join(', ')}.`,
455
532
  };
456
533
  }
457
534
 
@@ -546,15 +623,31 @@ export function checkIntegrationIssues(ctx) {
546
623
  id: 'integration-issues',
547
624
  label: 'Integration contributions',
548
625
  status: 'info',
549
- message: 'Skipped — the project integration graph could not be loaded.',
626
+ message: skippedBecause(
627
+ ctx,
628
+ 'the project integration graph could not be loaded',
629
+ ),
550
630
  };
551
631
  }
552
632
  if (issues.length === 0) {
633
+ // "No problems" is a finding only when something was looked at.
634
+ const checked = (ctx.integrations ?? []).filter(
635
+ integration => integration.__loadError == null,
636
+ );
637
+ if (checked.length === 0) {
638
+ return {
639
+ id: 'integration-issues',
640
+ label: 'Integration contributions',
641
+ status: 'info',
642
+ message:
643
+ 'No integration is loaded, so there are no integration contributions to check.',
644
+ };
645
+ }
553
646
  return {
554
647
  id: 'integration-issues',
555
648
  label: 'Integration contributions',
556
649
  status: 'pass',
557
- message: 'Integration contributions and cross-package relationships are valid.',
650
+ message: `${checked.length} loaded integration${checked.length === 1 ? '' : 's'} checked (${nameIntegrations(checked)}): contributions and cross-package relationships are valid.`,
558
651
  };
559
652
  }
560
653
  const errors = issues.filter(issue => issue.severity === 'error').length;
@@ -651,7 +744,7 @@ export function checkProviderIdentity(ctx) {
651
744
  id,
652
745
  label,
653
746
  status: 'info',
654
- message: 'Skipped — the project configuration could not be read.',
747
+ message: skippedBecause(ctx, 'the project configuration could not be read'),
655
748
  };
656
749
  }
657
750
 
@@ -1151,33 +1244,48 @@ export async function runChecks(options = {}) {
1151
1244
  let integrationIssues = null;
1152
1245
  /** @type {Array<{spec: string, error: string}>|null} */
1153
1246
  let autolinkFailures = null;
1247
+ /** @type {string|null} */
1248
+ let projectError = null;
1249
+ /** @type {import('../../foundation/config/project.mjs').Project | null} */
1250
+ let project = null;
1154
1251
  try {
1155
- const project = await Project.load(cwd);
1156
- integrations = project.loadedIntegrations;
1157
- // An installed dependency whose manifest cannot be loaded is kept out of
1158
- // loadedIntegrations on purpose. The provider ledger still records it.
1159
- autolinkFailures = [...providerLedgerOf(project).values()]
1160
- .filter(
1161
- entry =>
1162
- entry.outcome === 'load-failed' &&
1163
- entry.candidate.source === 'autolinked',
1164
- )
1165
- .map(entry => ({
1166
- spec: entry.candidate.spec ?? entry.label,
1167
- error: entry.error ?? 'its manifest could not be loaded',
1168
- }));
1252
+ project = await Project.load(cwd);
1253
+ } catch (err) {
1254
+ // A project the CLI cannot load leaves the checks that need it
1255
+ // skipped. The reason is kept: those checks and the config
1256
+ // check quote it, so a skip is never silent.
1257
+ projectError = err instanceof Error ? err.message : String(err);
1258
+ }
1259
+ if (project) {
1169
1260
  try {
1170
- docsCatalog = await project.docs();
1171
- docsCatalogIssues = (await project.issues()).filter(
1172
- issue => issue.code === 'invalid_doc',
1173
- );
1174
- } catch (err) {
1175
- docsCatalog = null;
1176
- docsCatalogError = err instanceof Error ? err.message : String(err);
1261
+ integrations = project.loadedIntegrations;
1262
+ // An installed dependency whose manifest cannot be loaded is kept out of
1263
+ // loadedIntegrations on purpose. The provider ledger still records it.
1264
+ autolinkFailures = [...providerLedgerOf(project).values()]
1265
+ .filter(
1266
+ entry =>
1267
+ entry.outcome === 'load-failed' &&
1268
+ entry.candidate.source === 'autolinked',
1269
+ )
1270
+ .map(entry => ({
1271
+ spec: entry.candidate.spec ?? entry.label,
1272
+ error: entry.error ?? 'its manifest could not be loaded',
1273
+ }));
1274
+ try {
1275
+ docsCatalog = await project.docs();
1276
+ docsCatalogIssues = (await project.issues()).filter(
1277
+ issue => issue.code === 'invalid_doc',
1278
+ );
1279
+ } catch (err) {
1280
+ docsCatalog = null;
1281
+ docsCatalogError = err instanceof Error ? err.message : String(err);
1282
+ }
1283
+ integrationIssues = await project.issues();
1284
+ } catch {
1285
+ // Best-effort: once the project has loaded, a later read that throws
1286
+ // leaves the remaining fields at their defaults. It is no reason to
1287
+ // blame the config, so it never becomes projectError.
1177
1288
  }
1178
- integrationIssues = await project.issues();
1179
- } catch {
1180
- // Best-effort: a missing or invalid config leaves integrations unavailable.
1181
1289
  }
1182
1290
 
1183
1291
  /** @type {DoctorContext} */
@@ -1193,6 +1301,7 @@ export async function runChecks(options = {}) {
1193
1301
  integrationIssues,
1194
1302
  autolinkFailures,
1195
1303
  configError,
1304
+ projectError,
1196
1305
  };
1197
1306
 
1198
1307
  /** @type {DoctorCheck[]} */
@@ -1018,3 +1018,107 @@ describe('doctor says what it could not check', () => {
1018
1018
  expect(check.message).toContain('could not be read');
1019
1019
  });
1020
1020
  });
1021
+
1022
+ describe('doctor says why it skipped and what it checked', () => {
1023
+ const CORE_STUB = {
1024
+ 'node_modules/@astryxdesign/core/package.json': JSON.stringify({
1025
+ name: '@astryxdesign/core',
1026
+ version: '0.6.3',
1027
+ }),
1028
+ };
1029
+
1030
+ /** A project under the working directory, so its config can be imported. */
1031
+ function cwdProject(files) {
1032
+ const dir = fs.mkdtempSync(
1033
+ path.join(process.cwd(), '.astryx-doctor-shape-'),
1034
+ );
1035
+ tmpDirs.push(dir);
1036
+ for (const [rel, content] of Object.entries(files)) {
1037
+ const abs = path.join(dir, rel);
1038
+ fs.mkdirSync(path.dirname(abs), {recursive: true});
1039
+ fs.writeFileSync(abs, content);
1040
+ }
1041
+ return dir;
1042
+ }
1043
+
1044
+ it(
1045
+ 'warns, and quotes the reason, when the CLI cannot load the project from a config that imports',
1046
+ async () => {
1047
+ const dir = cwdProject({
1048
+ 'package.json': '{"name":"app"}',
1049
+ ...CORE_STUB,
1050
+ 'astryx.config.mjs': "export default { integrations: 'oops' };\n",
1051
+ });
1052
+ const {checks, summary} = (await doctor({cwd: dir})).data;
1053
+ const by = Object.fromEntries(checks.map(c => [c.id, c]));
1054
+ expect(by.config.status).toBe('warn');
1055
+ expect(by.config.message).toMatch(
1056
+ /^astryx\.config\.mjs loads, but the CLI could not load the project from it: .*integrations/,
1057
+ );
1058
+ expect(by.config.fix).toContain('astryx docs authoring config');
1059
+ for (const id of ['implicit-integrations', 'provider-identity']) {
1060
+ expect(by[id].message).toMatch(
1061
+ /^Skipped — the project configuration could not be read: .*integrations/,
1062
+ );
1063
+ }
1064
+ expect(by['integration-issues'].message).toMatch(
1065
+ /^Skipped — the project integration graph could not be loaded: .*integrations/,
1066
+ );
1067
+ // A warning: the exit code a released CLI gave this project is unchanged.
1068
+ expect(summary.fail).toBe(0);
1069
+ },
1070
+ SLOW,
1071
+ );
1072
+
1073
+ it(
1074
+ 'passes the config check when the CLI loads the project from it',
1075
+ async () => {
1076
+ const dir = cwdProject({
1077
+ 'package.json': '{"name":"app"}',
1078
+ ...CORE_STUB,
1079
+ 'astryx.config.mjs': 'export default { integrations: [] };\n',
1080
+ });
1081
+ const by = Object.fromEntries(
1082
+ (await doctor({cwd: dir})).data.checks.map(c => [c.id, c]),
1083
+ );
1084
+ expect(by.config.status).toBe('pass');
1085
+ expect(by['implicit-integrations'].message).not.toContain('Skipped');
1086
+ },
1087
+ SLOW,
1088
+ );
1089
+
1090
+ it('says there is nothing to check when no integration is loaded', () => {
1091
+ expect(
1092
+ checkIntegrationIssues({integrationIssues: [], integrations: []}),
1093
+ ).toEqual({
1094
+ id: 'integration-issues',
1095
+ label: 'Integration contributions',
1096
+ status: 'info',
1097
+ message:
1098
+ 'No integration is loaded, so there are no integration contributions to check.',
1099
+ });
1100
+ });
1101
+
1102
+ it('names what it checked when every loaded integration is clean', () => {
1103
+ expect(
1104
+ checkIntegrationIssues({
1105
+ integrationIssues: [],
1106
+ integrations: [{name: '@acme/widgets'}],
1107
+ }),
1108
+ ).toMatchObject({
1109
+ status: 'pass',
1110
+ message:
1111
+ '1 loaded integration checked (@acme/widgets): contributions and cross-package relationships are valid.',
1112
+ });
1113
+ });
1114
+
1115
+ it('bounds the names it lists', () => {
1116
+ const integrations = Array.from({length: 12}, (_, i) => ({
1117
+ name: `@acme/kit-${i}`,
1118
+ }));
1119
+ const c = checkIntegrationIssues({integrationIssues: [], integrations});
1120
+ expect(c.message).toMatch(
1121
+ /^12 loaded integrations checked \(.* and 2 more\): /,
1122
+ );
1123
+ });
1124
+ });
@@ -15,6 +15,7 @@ export const doc = {
15
15
  summary:
16
16
  'Report a missing or hard-to-use design-system capability to the package that owns it.',
17
17
  description:
18
+ 'Routes the report to the package that owns the gap: options.package when given, else the integration whose component replaces the named Core component, else the one package that provides the component, else Core. ' +
18
19
  'Sends a gap report to every configured handler: the project config handler first, then each integration handler in config order. ' +
19
20
  'Each handler has 30 s to finish, and its output goes to stderr. Public handlers run only with confirmPublic; internal handlers always run. ' +
20
21
  "With no handler, it files a GitHub issue for the owning package only with confirmPublic (without it nothing is sent), or returns the package's issues URL when that is not on GitHub. " +
@@ -60,7 +61,7 @@ export const doc = {
60
61
  name: 'options.package',
61
62
  type: 'string',
62
63
  description:
63
- 'Package that owns the gap: @astryxdesign/core, or a loaded integration by package name or config entry. Overrides automatic owner routing; required when more than one package provides the component.',
64
+ 'Package that owns the gap: @astryxdesign/core, or a loaded integration by package name or config entry. Overrides automatic owner routing, which picks the integration whose component replaces the named Core component, else the one package that provides it, else Core; required when more than one package provides the component.',
64
65
  },
65
66
  {
66
67
  name: 'options.confirmPublic',
@@ -57,6 +57,7 @@ import {
57
57
  validateLoadedIntegration,
58
58
  issueError as error,
59
59
  issueWarning as warning,
60
+ rootProblem,
60
61
  } from '../../foundation/integrations/validate-contributions.mjs';
61
62
 
62
63
  export {validateLoadedIntegration};
@@ -161,9 +162,24 @@ async function findUnreachableContributionIssues(packageDir, loaded) {
161
162
  /** @param {string} dir */
162
163
  async function walk(dir) {
163
164
  if (roots.some(root => pathIsInside(dir, root))) return;
164
- const entries = fs
165
- .readdirSync(dir, {withFileTypes: true})
166
- .sort((a, b) => a.name.localeCompare(b.name));
165
+ let entries;
166
+ try {
167
+ entries = fs
168
+ .readdirSync(dir, {withFileTypes: true})
169
+ .sort((a, b) => a.name.localeCompare(b.name));
170
+ } catch (err) {
171
+ // One folder the user running astryx cannot read must not end the whole
172
+ // validation: name it and keep checking the rest of the package.
173
+ const shown = `${path.relative(packageDir, dir).split(path.sep).join('/') || '.'}/`;
174
+ const reason = /** @type {any} */ (err)?.code ?? String(err);
175
+ issues.push(
176
+ warning(
177
+ 'unreadable_folder',
178
+ `Could not read "${shown}" (${reason}), so it was not checked for contributions outside a declared root. Fix: make it readable by the user running astryx, or remove it if it does not belong in the package.`,
179
+ ),
180
+ );
181
+ return;
182
+ }
167
183
  for (const entry of entries) {
168
184
  if (truncated) return;
169
185
  if (UNREACHABLE_SKIP_DIRS.has(entry.name)) continue;
@@ -312,7 +328,7 @@ async function validateAtPackageDir(
312
328
  // Roots + contribution checks are shared with validateLoadedIntegration so
313
329
  // the everyday-command nudge runs the exact same validators.
314
330
  issues.push(...(await validateLoadedIntegration(loaded)));
315
- if (loaded.themes)
331
+ if (loaded.themes && !rootProblem(loaded.themes))
316
332
  issues.push(...unreadThemeFolderIssues(packageDir, loaded));
317
333
  if (scanUnreachable) {
318
334
  issues.push(
@@ -680,3 +680,76 @@ describe('validated separates "checked and clean" from "never checked"', () => {
680
680
  expect(summarizeIssues(res.data.issues).errors).toBeGreaterThan(0);
681
681
  });
682
682
  });
683
+
684
+ describe('unreadable folders are reported, never fatal', () => {
685
+ // Root reads every folder, so permission cases cannot be staged as root.
686
+ const asRoot = typeof process.getuid === 'function' && process.getuid() === 0;
687
+ /** @type {string[]} */
688
+ const locked = [];
689
+ afterEach(() => {
690
+ while (locked.length) fs.chmodSync(locked.pop(), 0o755);
691
+ });
692
+ /** @param {string} dir */
693
+ const lock = dir => {
694
+ fs.chmodSync(dir, 0o000);
695
+ locked.push(dir);
696
+ };
697
+
698
+ it.skipIf(asRoot)(
699
+ 'names a folder it cannot read and checks the rest of the package',
700
+ async () => {
701
+ const pkgDir = path.join(tmpDir, 'pkg');
702
+ writePackage(pkgDir, {
703
+ manifest: "export default { components: './components' };\n",
704
+ });
705
+ fs.mkdirSync(path.join(pkgDir, 'components'));
706
+ fs.mkdirSync(path.join(pkgDir, 'cache'));
707
+ lock(path.join(pkgDir, 'cache'));
708
+ const result = await validateLocalIntegration(pkgDir);
709
+ expect(byCode(result.issues, 'unreadable_folder')).toEqual([
710
+ expect.objectContaining({
711
+ severity: 'warning',
712
+ message: expect.stringContaining('Could not read "cache/" (EACCES)'),
713
+ }),
714
+ ]);
715
+ expect(summarizeIssues(result.issues).errors).toBe(0);
716
+ },
717
+ );
718
+
719
+ it.skipIf(asRoot)(
720
+ 'reports a declared root it cannot read as unreadable_root',
721
+ async () => {
722
+ const pkgDir = path.join(tmpDir, 'pkg');
723
+ writePackage(pkgDir, {
724
+ manifest:
725
+ "export default { codemods: './codemods', themes: './themes' };\n",
726
+ });
727
+ fs.mkdirSync(path.join(pkgDir, 'codemods'));
728
+ fs.mkdirSync(path.join(pkgDir, 'themes'));
729
+ lock(path.join(pkgDir, 'codemods'));
730
+ lock(path.join(pkgDir, 'themes'));
731
+ const result = await validateLocalIntegration(pkgDir);
732
+ expect(
733
+ byCode(result.issues, 'unreadable_root').map(issue => issue.message),
734
+ ).toEqual([
735
+ expect.stringMatching(/^Declared codemods root cannot be read \(EACCES\)/),
736
+ expect.stringMatching(/^Declared themes root cannot be read \(EACCES\)/),
737
+ ]);
738
+ },
739
+ );
740
+
741
+ it('reports a declared root that is a file as invalid_root', async () => {
742
+ const pkgDir = path.join(tmpDir, 'pkg');
743
+ writePackage(pkgDir, {
744
+ manifest: "export default { codemods: './codemods.mjs' };\n",
745
+ });
746
+ fs.writeFileSync(path.join(pkgDir, 'codemods.mjs'), 'export default {};\n');
747
+ const result = await validateLocalIntegration(pkgDir);
748
+ expect(byCode(result.issues, 'invalid_root')).toEqual([
749
+ expect.objectContaining({
750
+ severity: 'error',
751
+ message: expect.stringContaining('is a file, not a folder'),
752
+ }),
753
+ ]);
754
+ });
755
+ });
@@ -24,6 +24,50 @@ export function sameWord(a: string, b: string): boolean;
24
24
  * @returns {string[]}
25
25
  */
26
26
  export function tokenizeQuery(term: string): string[];
27
+ /**
28
+ * A match's domain priority: 0 (none), 1, or 2 (a doc the whole query names).
29
+ * A component, hook, template, or theme with priority ranks ahead of any doc
30
+ * without it, whatever the two scores are. Docs among themselves rank by
31
+ * priority, then score; everything else ranks among itself by score.
32
+ *
33
+ * A component, hook, template, or theme has priority (1) when one of the
34
+ * query's words, or the whole query, hits its name or an authored keyword at
35
+ * {@link STRONG_TOKEN_SCORE} or above, or when it matches every word.
36
+ *
37
+ * A doc has priority when the reader asked for that doc:
38
+ * - 2: the whole query is the topic's name, its last route segment, or its
39
+ * own title, as words and whatever the plural (`font setup` is
40
+ * typography/font-setup, `side panel` is "Side panels");
41
+ * - 1: a word of the query is the topic's name (`illustration` in a longer
42
+ * question is the illustrations guide);
43
+ * - 1: the query holds one of the doc's titles whole (`resizable side panels`
44
+ * names "Side panels"; `light dark mode button` names "Light/Dark Mode");
45
+ * - 1: the doc matches every word of the query and one of them is a word of
46
+ * its title (`switch to a dark theme` and "Use a theme").
47
+ * A section answers to its topic's name.
48
+ *
49
+ * A doc that matched only by keyword, by a heading holding the query, or by
50
+ * words spread through its text has no priority. Docs are split into many
51
+ * small topics, and each declares its own keywords and headings, so a common
52
+ * phrase such as `font size` hits a guide's keyword or heading exactly
53
+ * (170-190) while the component the reader is after matches one word by
54
+ * keyword (`Text`, 98). Ranked on text alone, every split adds another doc
55
+ * above the component. Broad reference pages match every word of many queries
56
+ * in their text the same way. The score stays the text-match strength the
57
+ * result reports, so callers that gate on it (`build`) see the same numbers.
58
+ *
59
+ * @param {string} term - Lowercased search term.
60
+ * @param {string[]} tokens - Content tokens from tokenizeQuery(term).
61
+ * @param {Candidate} candidate
62
+ * @param {{score: number, matched: number, total: number}} hit - The
63
+ * candidate's scoreQuery result.
64
+ * @returns {0 | 1 | 2}
65
+ */
66
+ export function domainPriority(term: string, tokens: string[], candidate: Candidate, hit: {
67
+ score: number;
68
+ matched: number;
69
+ total: number;
70
+ }): 0 | 1 | 2;
27
71
  /**
28
72
  * The first title or heading that holds every word of the query, in order and
29
73
  * side by side, or null.