@astryxdesign/cli 0.7.2-canary.64e1dde → 0.7.2-canary.6c792d8

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 (71) 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/detail/doc/doc.mjs +9 -1
  7. package/api/docs/_adapter.d.mts +63 -0
  8. package/api/docs/_adapter.mjs +309 -16
  9. package/api/docs/integration-tree.test.mjs +22 -0
  10. package/api/docs/list/list.mjs +12 -2
  11. package/api/integration/_adapter.d.mts +23 -0
  12. package/api/integration/_adapter.mjs +45 -0
  13. package/api/integration/authoring-checks.mjs +87 -3
  14. package/api/integration/authoring-checks.test.mjs +443 -0
  15. package/api/integration/authoring-checks.type.d.mts +84 -0
  16. package/api/integration/authoring-checks.type.mjs +40 -1
  17. package/api/integration/integrationComponentConflicts.doc.mjs +3 -1
  18. package/api/integration/integrationDocConflicts.doc.mjs +7 -2
  19. package/api/integration/pack-check.mjs +4 -0
  20. package/api/integration/pack-check.test.mjs +26 -0
  21. package/api/integration/validate-integration-fixes.test.mjs +67 -0
  22. package/api/integration/validate-integration.mjs +28 -3
  23. package/api/integration/validate-integration.test.mjs +77 -8
  24. package/api/integration/validateIntegration.doc.mjs +1 -1
  25. package/api/search/search.mjs +2 -1
  26. package/assets/docs/browser-support.doc.mjs +1 -1
  27. package/assets/docs/tree/add-a-topic.doc.mjs +2 -2
  28. package/assets/docs/tree/check-the-props.doc.mjs +5 -0
  29. package/assets/docs/tree/check-your-docs.doc.mjs +10 -2
  30. package/assets/docs/tree/checks.doc.mjs +4 -4
  31. package/assets/docs/tree/debug-and-gap-reports.doc.mjs +7 -7
  32. package/assets/docs/tree/document-the-theme.doc.mjs +2 -2
  33. package/assets/docs/tree/publishing.doc.mjs +2 -2
  34. package/assets/docs/tree/sections-and-placement.doc.mjs +2 -2
  35. package/authoring/doctypes/component/type.ts +8 -0
  36. package/authoring/doctypes/hook/type.ts +4 -0
  37. package/clients/cli/commands/doctor-integration-components.doc.mjs +3 -2
  38. package/clients/cli/commands/doctor-integration-docs.doc.mjs +3 -1
  39. package/clients/cli/commands/doctor-integration.test.mjs +48 -1
  40. package/clients/cli/commands/doctor.mjs +60 -5
  41. package/clients/cli/commands/integration-authoring.test.mjs +46 -0
  42. package/clients/cli/commands/integration-check.test.mjs +79 -0
  43. package/clients/cli/commands/integration.mjs +10 -4
  44. package/foundation/discovery/copied-passages.d.mts +8 -0
  45. package/foundation/discovery/copied-passages.mjs +2 -2
  46. package/foundation/discovery/doc-consistency.d.mts +34 -0
  47. package/foundation/discovery/doc-consistency.mjs +513 -0
  48. package/foundation/discovery/doc-consistency.test.mjs +347 -0
  49. package/foundation/discovery/doc-fluff.d.mts +112 -0
  50. package/foundation/discovery/doc-fluff.mjs +328 -0
  51. package/foundation/discovery/doc-fluff.test.mjs +142 -0
  52. package/foundation/discovery/doc-types.mjs +12 -5
  53. package/foundation/discovery/doc-types.test.mjs +46 -2
  54. package/foundation/discovery/prop-drift.d.mts +25 -6
  55. package/foundation/discovery/prop-drift.mjs +171 -6
  56. package/foundation/discovery/prop-drift.test.mjs +65 -0
  57. package/foundation/discovery/stray-pointers.d.mts +52 -0
  58. package/foundation/discovery/stray-pointers.mjs +293 -0
  59. package/foundation/discovery/stray-pointers.test.mjs +86 -0
  60. package/foundation/doc-compiler/doc-loads.test.mjs +12 -0
  61. package/foundation/doc-compiler/links.d.mts +32 -0
  62. package/foundation/doc-compiler/links.mjs +163 -26
  63. package/foundation/doc-compiler/links.test.mjs +97 -4
  64. package/foundation/doc-compiler/tree.mjs +30 -1
  65. package/foundation/doc-compiler/tree.test.mjs +7 -0
  66. package/foundation/integrations/contribution-inventory.d.mts +11 -0
  67. package/foundation/integrations/contribution-inventory.mjs +50 -2
  68. package/foundation/integrations/issue.ts +6 -0
  69. package/foundation/integrations/validate-contributions.mjs +30 -1
  70. package/foundation/response/response-types.doc.mjs +4 -4
  71. package/package.json +9 -9
@@ -31,7 +31,11 @@
31
31
  * each);
32
32
  * - `type_mismatch`: for a prop declared in the package, the documented type
33
33
  * differs from the code's where both sides read exactly (type-match.mjs
34
- * states the rules); every other type is listed as not compared.
34
+ * states the rules); every other type is listed as not compared;
35
+ * - `default_mismatch`: the doc's `default` and the literal default the
36
+ * component writes in its props parameter's destructuring (`size = 'md'`)
37
+ * differ, quotes and whitespace aside; where both write a default and
38
+ * either is not a literal, it is listed under `typesNotCompared`.
35
39
  *
36
40
  * @input Component records (name, docPath, sourcePath), or prop tables, the
37
41
  * package root, and the directories to resolve `typescript` from.
@@ -58,7 +62,7 @@ import {
58
62
  } from './unresolved-references.mjs';
59
63
 
60
64
  /**
61
- * @typedef {'not_in_code' | 'not_in_doc' | 'required_mismatch' | 'type_mismatch'} PropDriftKind
65
+ * @typedef {'not_in_code' | 'not_in_doc' | 'required_mismatch' | 'type_mismatch' | 'default_mismatch'} PropDriftKind
62
66
  */
63
67
 
64
68
  /**
@@ -74,6 +78,9 @@ import {
74
78
  * @property {string} [codeType] the type as the source declares it
75
79
  * @property {boolean} [docRequired]
76
80
  * @property {boolean} [codeRequired]
81
+ * @property {string} [docDefault] the documented default, as written
82
+ * @property {string} [codeDefault] the literal default the code writes
83
+ * @property {string} [fix] what to change, ready to paste
77
84
  */
78
85
 
79
86
  /**
@@ -89,8 +96,10 @@ import {
89
96
  * @property {string} doc the doc file, relative to the package root
90
97
  * @property {string} reason why: not a form the check judges exactly, a
91
98
  * field the prop's variants give different types, a standard prop
92
- * (`className`, `style`, …), or a prop declared outside the package
93
- * @property {string[]} props documented props whose types were not compared
99
+ * (`className`, `style`, …), a prop declared outside the package, or a
100
+ * default that is not a literal on one side
101
+ * @property {string[]} props documented props whose types, or defaults, were
102
+ * not compared
94
103
  */
95
104
 
96
105
  /**
@@ -149,6 +158,15 @@ const SKIP_TAGS = new Set(['internal']);
149
158
  const NOT_EXACT = 'not a form the check judges exactly';
150
159
  /** A field documented with one variant's type, where they differ. */
151
160
  const VARIANTS = "the prop's variants give this field different types";
161
+
162
+ /** A default the code writes that is not a literal (a constant, a call). */
163
+ const NOT_LITERAL = Symbol('not a literal');
164
+
165
+ /** Why a documented default was not compared with the code's. */
166
+ const CODE_DEFAULT_NOT_LITERAL =
167
+ 'its default in the code is not a literal, so the documented default was not compared';
168
+ const DOC_DEFAULT_NOT_LITERAL =
169
+ "its documented default is not a literal, so it was not compared with the code's";
152
170
  /** @type {(name: string, code?: CodeProp) => string} why a prop is not judged */
153
171
  const outside = (name, code) =>
154
172
  code?.untraced
@@ -252,7 +270,7 @@ function ownFileTest(root) {
252
270
  * @param {import('./unresolved-references.mjs').UnresolvedReference | null} ambient
253
271
  * what the program's other roots cannot resolve, which any component may
254
272
  * use
255
- * @returns {{ok: true, props: Map<string, CodeProp>, accepts: (name: string) => any} | {ok: false, reason: string}}
273
+ * @returns {{ok: true, props: Map<string, CodeProp>, accepts: (name: string) => any, defaults?: Map<string, string | number | boolean | null | symbol>} | {ok: false, reason: string}}
256
274
  */
257
275
  function readCodeProps(
258
276
  ts,
@@ -580,7 +598,118 @@ function readCodeProps(
580
598
  /** The index signatures of the props type that take this name. */
581
599
  const accepts = (/** @type {string} */ name) =>
582
600
  indexesFor(ts, checker, members, name);
583
- return {ok: true, props, accepts};
601
+ return {ok: true, props, accepts, defaults: literalDefaults(ts, symbol)};
602
+ }
603
+
604
+ /**
605
+ * The defaults a component writes in its props parameter's destructuring
606
+ * (`{size = 'md'}`), by prop name, each as its value: a string, number,
607
+ * boolean, or null, or NOT_LITERAL for any other default (a constant, a call,
608
+ * an object), which is listed as not compared.
609
+ * @param {any} ts
610
+ * @param {any} symbol the component
611
+ * @returns {Map<string, string | number | boolean | null | symbol>}
612
+ */
613
+ function literalDefaults(ts, symbol) {
614
+ /** @type {Map<string, string | number | boolean | null | symbol>} */
615
+ const out = new Map();
616
+ /** @param {any} node @param {number} depth @returns {any} */
617
+ const fnOf = (node, depth) => {
618
+ if (!node || depth > 4) return null;
619
+ if (
620
+ ts.isFunctionDeclaration(node) ||
621
+ ts.isArrowFunction(node) ||
622
+ ts.isFunctionExpression(node)
623
+ ) {
624
+ return node;
625
+ }
626
+ if (ts.isVariableDeclaration(node))
627
+ return fnOf(node.initializer, depth + 1);
628
+ if (
629
+ ts.isParenthesizedExpression(node) ||
630
+ ts.isAsExpression(node) ||
631
+ (ts.isSatisfiesExpression && ts.isSatisfiesExpression(node))
632
+ ) {
633
+ return fnOf(node.expression, depth + 1);
634
+ }
635
+ // `forwardRef(function …)`, `memo(…)`: the function they wrap.
636
+ if (ts.isCallExpression(node)) {
637
+ for (const argument of node.arguments) {
638
+ const found = fnOf(argument, depth + 1);
639
+ if (found) return found;
640
+ }
641
+ }
642
+ return null;
643
+ };
644
+ const fn = fnOf(symbol?.valueDeclaration, 0);
645
+ const pattern = fn?.parameters?.[0]?.name;
646
+ if (!pattern || !ts.isObjectBindingPattern(pattern)) return out;
647
+ for (const element of pattern.elements) {
648
+ if (element.dotDotDotToken || !element.initializer) continue;
649
+ const key = element.propertyName ?? element.name;
650
+ if (!(
651
+ ts.isIdentifier(key) ||
652
+ ts.isStringLiteral(key) ||
653
+ ts.isNumericLiteral(key)
654
+ )) {
655
+ continue;
656
+ }
657
+ const value = literalValue(ts, element.initializer);
658
+ out.set(key.text, value === undefined ? NOT_LITERAL : value);
659
+ }
660
+ return out;
661
+ }
662
+
663
+ /**
664
+ * A literal expression's value, or undefined for anything else.
665
+ * @param {any} ts
666
+ * @param {any} node
667
+ * @returns {string | number | boolean | null | undefined}
668
+ */
669
+ function literalValue(ts, node) {
670
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) {
671
+ return node.text;
672
+ }
673
+ if (ts.isNumericLiteral(node)) return Number(node.text);
674
+ if (
675
+ ts.isPrefixUnaryExpression(node) &&
676
+ node.operator === ts.SyntaxKind.MinusToken &&
677
+ ts.isNumericLiteral(node.operand)
678
+ ) {
679
+ return -Number(node.operand.text);
680
+ }
681
+ if (node.kind === ts.SyntaxKind.TrueKeyword) return true;
682
+ if (node.kind === ts.SyntaxKind.FalseKeyword) return false;
683
+ if (node.kind === ts.SyntaxKind.NullKeyword) return null;
684
+ return undefined;
685
+ }
686
+
687
+ /**
688
+ * A documented default as a literal value: a quoted string (quotes of any
689
+ * kind, whitespace around it ignored), a number, `true`, `false`, or
690
+ * `null`; undefined for prose or an expression, which is never compared.
691
+ * @param {unknown} written
692
+ * @returns {string | number | boolean | null | undefined}
693
+ */
694
+ function documentedDefault(written) {
695
+ if (typeof written === 'number' || typeof written === 'boolean') {
696
+ return written;
697
+ }
698
+ if (written === null) return null;
699
+ if (typeof written !== 'string') return undefined;
700
+ const text = written.trim();
701
+ const quoted = /^(['"`])([^'"`]*)\1$/.exec(text);
702
+ if (quoted) return quoted[2];
703
+ if (/^-?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(text)) return Number(text);
704
+ if (text === 'true') return true;
705
+ if (text === 'false') return false;
706
+ if (text === 'null') return null;
707
+ return undefined;
708
+ }
709
+
710
+ /** @param {string | number | boolean | null} value */
711
+ function defaultText(value) {
712
+ return typeof value === 'string' ? `'${value}'` : String(value);
584
713
  }
585
714
 
586
715
  /**
@@ -1952,6 +2081,42 @@ export function comparePropTables(tables, options) {
1952
2081
  codeRequired: code.required,
1953
2082
  });
1954
2083
  }
2084
+ // A literal default the code writes in its props destructuring and a
2085
+ // literal the doc writes must agree; where both write a default and
2086
+ // either is not a literal, the default is listed as not compared.
2087
+ const codeDefault = read.defaults?.get(propName);
2088
+ const docWrites =
2089
+ entries.length === 1 &&
2090
+ raw.default !== undefined &&
2091
+ raw.default !== '';
2092
+ const docDefault = docWrites
2093
+ ? documentedDefault(raw.default)
2094
+ : undefined;
2095
+ if (codeDefault !== undefined && docWrites) {
2096
+ if (codeDefault === NOT_LITERAL) {
2097
+ skip(CODE_DEFAULT_NOT_LITERAL, propName);
2098
+ } else if (docDefault === undefined) {
2099
+ skip(DOC_DEFAULT_NOT_LITERAL, propName);
2100
+ }
2101
+ }
2102
+ if (
2103
+ codeDefault !== undefined &&
2104
+ codeDefault !== NOT_LITERAL &&
2105
+ docDefault !== undefined &&
2106
+ codeDefault !== docDefault
2107
+ ) {
2108
+ const shown = defaultText(
2109
+ /** @type {string | number | boolean | null} */ (codeDefault),
2110
+ );
2111
+ findings.push({
2112
+ ...base,
2113
+ kind: 'default_mismatch',
2114
+ message: `"${propName}" is documented with default ${String(raw.default).trim()}, but the code defaults it to ${shown}.`,
2115
+ fix: `In ${table.doc}, set the "${propName}" prop's default to the code's: default: ${JSON.stringify(shown)}.`,
2116
+ docDefault: String(raw.default),
2117
+ codeDefault: shown,
2118
+ });
2119
+ }
1955
2120
  if (!code.own && typeof entry.type === 'string') {
1956
2121
  skip(outside(propName, code), propName);
1957
2122
  }
@@ -366,6 +366,71 @@ export function Badge(props: BadgeProps) { return null; }`,
366
366
  ).toMatchObject({docRequired: false, codeRequired: true});
367
367
  });
368
368
 
369
+ it('compares a documented default with a literal default in the props destructuring, quotes and whitespace aside, and skips any other default', async () => {
370
+ withTypeScript();
371
+ const widget = component(
372
+ 'Widget',
373
+ `const SIZE = 'md';
374
+ export interface WidgetProps { size?: 'sm' | 'md'; tone?: string; count?: number; open?: boolean; label?: string; gap?: number; mode?: string }
375
+ export function Widget({size = 'md', tone = "info", count = -2, open = false, label = SIZE, gap = 4, mode}: WidgetProps) { return null; }`,
376
+ {
377
+ props: [
378
+ prop('size', "'sm' | 'md'", {default: "'sm'"}),
379
+ prop('tone', 'string', {default: ' "info" '}),
380
+ prop('count', 'number', {default: '-2'}),
381
+ prop('open', 'boolean', {default: 'true'}),
382
+ prop('label', 'string', {default: "'x'"}),
383
+ prop('gap', 'number', {default: 'the theme gap'}),
384
+ prop('mode', 'string', {default: "'a'"}),
385
+ ],
386
+ },
387
+ );
388
+ const forwarded = component(
389
+ 'Forwarded',
390
+ `declare function forwardRef<T>(render: T): T;
391
+ export const Forwarded = forwardRef(function Forwarded({variant = 'solid'}: {variant?: string}) { return null; });`,
392
+ {props: [prop('variant', 'string', {default: "'ghost'"})]},
393
+ );
394
+
395
+ const report = await compare([widget, forwarded]);
396
+
397
+ expect(kinds(report)).toEqual([
398
+ 'Forwarded.variant default_mismatch',
399
+ 'Widget.open default_mismatch',
400
+ 'Widget.size default_mismatch',
401
+ ]);
402
+ // A default that is not a literal on either side is listed, not skipped.
403
+ expect(report.typesNotCompared).toEqual(
404
+ expect.arrayContaining([
405
+ expect.objectContaining({
406
+ component: 'Widget',
407
+ reason: expect.stringContaining(
408
+ 'default in the code is not a literal',
409
+ ),
410
+ props: ['label'],
411
+ }),
412
+ expect.objectContaining({
413
+ component: 'Widget',
414
+ reason: expect.stringContaining(
415
+ 'documented default is not a literal',
416
+ ),
417
+ props: ['gap'],
418
+ }),
419
+ ]),
420
+ );
421
+ expect(report.typesNotCompared.flatMap(entry => entry.props)).not.toContain(
422
+ 'mode',
423
+ );
424
+ expect(report.findings.find(f => f.prop === 'size')).toMatchObject({
425
+ severity: 'warning',
426
+ message:
427
+ "\"size\" is documented with default 'sm', but the code defaults it to 'md'.",
428
+ fix: 'In components/Widget.doc.mjs, set the "size" prop\'s default to the code\'s: default: "\'md\'".',
429
+ docDefault: "'sm'",
430
+ codeDefault: "'md'",
431
+ });
432
+ });
433
+
369
434
  it("judges a field, a name an index signature takes, and a prop declared in another file by the type's name where the prop is declared, not by the name the type was declared with", async () => {
370
435
  withTypeScript();
371
436
  const dir = path.join(pkg, 'components');
@@ -0,0 +1,52 @@
1
+ // @generated by scripts/sync-api-types.mjs from the JSDoc in foundation/**/*.mjs.
2
+ // DO NOT EDIT — run `pnpm sync:api-types` to regenerate.
3
+
4
+ /**
5
+ * The strings of a doc the CLI resolves links in (spec:AST-047 FR9). In a
6
+ * topic: its description and summary, then the text of prose and heading
7
+ * blocks, list items, and table cells in each section's content, with the
8
+ * section's title. In a component doc (any doc with no sections): every text
9
+ * field, such as its description, usage, best practices, and each prop's and
10
+ * example's description, with the field's path. Code is never read.
11
+ *
12
+ * @param {unknown} doc an authored doc object
13
+ * @returns {{text: string, section: string | null, field: string | null}[]}
14
+ */
15
+ export function linkableStrings(doc: unknown): {
16
+ text: string;
17
+ section: string | null;
18
+ field: string | null;
19
+ }[];
20
+ /**
21
+ * Every pointer span in one prose string, in order.
22
+ * @param {string} text
23
+ * @returns {string[]} the doc name each one points at
24
+ */
25
+ export function pointersIn(text: string): string[];
26
+ /**
27
+ * Each stray pointer in a package's topics and component docs.
28
+ *
29
+ * @param {{records: {name: string, path: string}[], guides?: {name: string, ref?: {topicFile?: string}}[], namespaces?: {doc?: {name?: string}}[], components?: {name: string, file: string}[]}} discovered
30
+ * @returns {Promise<import('../../api/integration/authoring-checks.type.mjs').StrayPointer[]>}
31
+ */
32
+ export function findStrayPointers(discovered: {
33
+ records: {
34
+ name: string;
35
+ path: string;
36
+ }[];
37
+ guides?: {
38
+ name: string;
39
+ ref?: {
40
+ topicFile?: string;
41
+ };
42
+ }[];
43
+ namespaces?: {
44
+ doc?: {
45
+ name?: string;
46
+ };
47
+ }[];
48
+ components?: {
49
+ name: string;
50
+ file: string;
51
+ }[];
52
+ }): Promise<import("../../api/integration/authoring-checks.type.mjs").StrayPointer[]>;
@@ -0,0 +1,293 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Stray doc pointers (architecture:cli-surface DEC-8): a code span in
5
+ * prose that is exactly `astryx docs <name>` for a doc that exists. The doc's
6
+ * `{@link}` prints the command that opens the doc and is checked by doctor's
7
+ * link check, so a written command is a pointer nothing checks.
8
+ *
9
+ * @input the docs a package ships, as discoverIntegrationDocs returns them
10
+ * @output each stray pointer, with the link that replaces it
11
+ * @position foundation/discovery, called through api/integration/_adapter.mjs
12
+ */
13
+
14
+ import fs from 'node:fs';
15
+
16
+ import {textFields} from '../doc-compiler/links.mjs';
17
+ import {builtinGuideFiles} from './docs-discovery.mjs';
18
+ import {
19
+ fileWords,
20
+ lineAtOffset,
21
+ loadQuietly,
22
+ locateWords,
23
+ textWords,
24
+ } from './copied-passages.mjs';
25
+
26
+ /**
27
+ * A code span that is exactly the command opening one doc. A command with
28
+ * more words, a flag, or a route is a walkthrough, not a pointer. A name holds
29
+ * what a topic name may (letters, digits, `_` and `-`), never opening with `-`.
30
+ */
31
+ const POINTER = /`astryx docs ([A-Za-z0-9_][A-Za-z0-9_-]*)`/g;
32
+
33
+ /** @type {Promise<Map<string, string>> | undefined} */
34
+ let coreKinds;
35
+
36
+ /**
37
+ * The CLI's own docs by name, each with the kind a link names it by: a
38
+ * namespace doc as `namespace`, a topic or guide as `generic`.
39
+ * @returns {Promise<Map<string, string>>}
40
+ */
41
+ function loadCoreKinds() {
42
+ coreKinds ??= (async () => {
43
+ const kinds = new Map();
44
+ for (const file of builtinGuideFiles()) {
45
+ const doc = await loadQuietly(file);
46
+ if (typeof doc?.name === 'string') {
47
+ kinds.set(doc.name, doc.type === 'namespace' ? 'namespace' : 'generic');
48
+ }
49
+ }
50
+ return kinds;
51
+ })();
52
+ return coreKinds;
53
+ }
54
+
55
+ /**
56
+ * The strings of a doc the CLI resolves links in (spec:AST-047 FR9). In a
57
+ * topic: its description and summary, then the text of prose and heading
58
+ * blocks, list items, and table cells in each section's content, with the
59
+ * section's title. In a component doc (any doc with no sections): every text
60
+ * field, such as its description, usage, best practices, and each prop's and
61
+ * example's description, with the field's path. Code is never read.
62
+ *
63
+ * @param {unknown} doc an authored doc object
64
+ * @returns {{text: string, section: string | null, field: string | null}[]}
65
+ */
66
+ export function linkableStrings(doc) {
67
+ /** @type {{text: string, section: string | null, field: string | null}[]} */
68
+ const strings = [];
69
+ if (doc == null || typeof doc !== 'object') return strings;
70
+ const top = /** @type {Record<string, any>} */ (doc);
71
+ if (!Array.isArray(top.sections)) {
72
+ for (const {field, text} of textFields(doc)) {
73
+ strings.push({text, section: null, field});
74
+ }
75
+ return strings;
76
+ }
77
+ for (const field of ['description', 'summary']) {
78
+ if (typeof top[field] === 'string') {
79
+ strings.push({text: top[field], section: null, field});
80
+ }
81
+ }
82
+ /**
83
+ * @param {unknown} value
84
+ * @param {string | null} section
85
+ */
86
+ const walk = (value, section) => {
87
+ if (Array.isArray(value)) {
88
+ for (const item of value) walk(item, section);
89
+ return;
90
+ }
91
+ if (value == null || typeof value !== 'object') return;
92
+ const record = /** @type {Record<string, any>} */ (value);
93
+ const title = typeof record.title === 'string' ? record.title : section;
94
+ if (Array.isArray(record.sections)) walk(record.sections, section);
95
+ if (!Array.isArray(record.content)) return;
96
+ for (const block of record.content) {
97
+ const add = (/** @type {unknown} */ text) => {
98
+ if (typeof text === 'string') {
99
+ strings.push({text, section: title, field: null});
100
+ }
101
+ };
102
+ switch (block?.type) {
103
+ case 'prose':
104
+ case 'heading':
105
+ add(block.text);
106
+ break;
107
+ case 'list':
108
+ (block.items ?? []).forEach(add);
109
+ break;
110
+ case 'table':
111
+ (block.headers ?? []).forEach(add);
112
+ for (const row of block.rows ?? []) row.forEach(add);
113
+ break;
114
+ default:
115
+ walk(block, title);
116
+ }
117
+ }
118
+ };
119
+ walk(doc, null);
120
+ return strings;
121
+ }
122
+
123
+ /**
124
+ * Every pointer span in one prose string, in order.
125
+ * @param {string} text
126
+ * @returns {string[]} the doc name each one points at
127
+ */
128
+ export function pointersIn(text) {
129
+ return [...text.matchAll(POINTER)].map(match => match[1]);
130
+ }
131
+
132
+ /**
133
+ * Where a string's words start among a file's words, from `from` on. A
134
+ * one-line string the file holds as a quoted literal is found at that
135
+ * literal, so a list item that is only `astryx docs theme` is not placed at a
136
+ * summary or code block that writes the same words.
137
+ *
138
+ * @param {string[]} lines the file's lines
139
+ * @param {{word: string, line: number}[]} file the file's words
140
+ * @param {string} text
141
+ * @param {{word: string}[]} words the string's words
142
+ * @param {number} from
143
+ * @returns {number}
144
+ */
145
+ function locateString(lines, file, text, words, from) {
146
+ /** @type {number[]} */
147
+ const starts = [];
148
+ for (let at = locateWords(file, words); at >= 0;) {
149
+ starts.push(at);
150
+ at = locateWords(file, words, at + 1);
151
+ }
152
+ if (starts.length === 0) return -1;
153
+ const literals = text.includes('\n')
154
+ ? []
155
+ : [`'${text}'`, `"${text}"`, `'${text.replace(/'/g, "\\'")}'`];
156
+ const quoted = starts.filter(at =>
157
+ literals.some(literal => lines[file[at].line - 1]?.includes(literal)),
158
+ );
159
+ const pool = quoted.length > 0 ? quoted : starts;
160
+ return pool.find(at => at >= from) ?? pool[0];
161
+ }
162
+
163
+ /**
164
+ * Each stray pointer in a package's topics and component docs.
165
+ *
166
+ * @param {{records: {name: string, path: string}[], guides?: {name: string, ref?: {topicFile?: string}}[], namespaces?: {doc?: {name?: string}}[], components?: {name: string, file: string}[]}} discovered
167
+ * @returns {Promise<import('../../api/integration/authoring-checks.type.mjs').StrayPointer[]>}
168
+ */
169
+ export async function findStrayPointers(discovered) {
170
+ /** @type {{name: string, file: string | undefined, kind: 'topic' | 'component'}[]} */
171
+ const topics = [
172
+ ...discovered.records.map(record => ({
173
+ name: record.name,
174
+ file: record.path,
175
+ kind: /** @type {const} */ ('topic'),
176
+ })),
177
+ ...(discovered.guides ?? []).map(guide => ({
178
+ name: guide.name,
179
+ file: guide.ref?.topicFile,
180
+ kind: /** @type {const} */ ('topic'),
181
+ })),
182
+ ];
183
+ /** @type {Map<string, string>} */
184
+ const own = new Map(topics.map(topic => [topic.name, 'generic']));
185
+ for (const namespace of discovered.namespaces ?? []) {
186
+ const name = namespace?.doc?.name;
187
+ if (typeof name === 'string' && !own.has(name)) own.set(name, 'namespace');
188
+ }
189
+ for (const component of discovered.components ?? []) {
190
+ topics.push({
191
+ name: component.name,
192
+ file: component.file,
193
+ kind: 'component',
194
+ });
195
+ }
196
+ const core = await loadCoreKinds();
197
+ // A topic that extends another has no route of its own: a link to it names
198
+ // the page it shows on, the topic it extends.
199
+ /** @type {Map<string, string>} */
200
+ const extendsOf = new Map();
201
+ for (const topic of topics) {
202
+ if (!topic.file) continue;
203
+ const doc = /** @type {any} */ (await loadQuietly(topic.file));
204
+ if (typeof doc?.extends === 'string')
205
+ extendsOf.set(topic.name, doc.extends);
206
+ }
207
+ /** @param {string} target */
208
+ const linkFor = target => {
209
+ const page = extendsOf.get(target);
210
+ if (page != null) {
211
+ if (own.has(page) && !extendsOf.has(page)) {
212
+ return `{@link ${own.get(page)}:${page}}`;
213
+ }
214
+ return core.has(page)
215
+ ? `{@link @astryxdesign/cli:${core.get(page)}:${page}}`
216
+ : null;
217
+ }
218
+ return own.has(target)
219
+ ? `{@link ${own.get(target)}:${target}}`
220
+ : core.has(target)
221
+ ? `{@link @astryxdesign/cli:${core.get(target)}:${target}}`
222
+ : null;
223
+ };
224
+ /** @type {import('../../api/integration/authoring-checks.type.mjs').StrayPointer[]} */
225
+ const found = [];
226
+ for (const topic of topics) {
227
+ if (!topic.file) continue;
228
+ const doc = await loadQuietly(topic.file);
229
+ if (!doc) continue;
230
+ /** @type {{word: string, line: number}[]} */
231
+ let source = [];
232
+ /** @type {string[]} */
233
+ let lines = [];
234
+ try {
235
+ const raw = fs.readFileSync(topic.file, 'utf8');
236
+ source = fileWords(raw);
237
+ lines = raw.split('\n');
238
+ } catch {
239
+ // No line numbers; the finding still names the section.
240
+ }
241
+ // A component doc is named by its own name: a family doc by the family.
242
+ const name =
243
+ topic.kind === 'component' && typeof doc.name === 'string'
244
+ ? doc.name
245
+ : topic.name;
246
+ const label =
247
+ topic.kind === 'component' ? `component "${name}"` : `"${name}"`;
248
+ // Each string is found by its whole run of words, from where the last
249
+ // one was found, so two strings that open alike keep their own lines.
250
+ let cursor = 0;
251
+ for (const {text, section, field} of linkableStrings(doc)) {
252
+ const words = textWords(text);
253
+ const index = locateString(lines, source, text, words, cursor);
254
+ if (index >= 0) cursor = index + words.length;
255
+ for (const match of text.matchAll(POINTER)) {
256
+ const target = match[1];
257
+ const link = linkFor(target);
258
+ if (!link) continue;
259
+ const command = `astryx docs ${target}`;
260
+ const line =
261
+ index < 0
262
+ ? null
263
+ : lineAtOffset(
264
+ source,
265
+ index,
266
+ words,
267
+ /** @type {number} */ (match.index) + 1,
268
+ );
269
+ const where = [
270
+ section ? `section "${section}"` : null,
271
+ field ? `field ${field}` : null,
272
+ line == null ? null : `line ${line}`,
273
+ ]
274
+ .filter(Boolean)
275
+ .join(', ');
276
+ found.push({
277
+ topic: name,
278
+ kind: topic.kind,
279
+ section,
280
+ field,
281
+ file: topic.file,
282
+ line,
283
+ pointer: command,
284
+ link,
285
+ message:
286
+ `${label}${where ? ` (${where})` : ''} points at a doc with the written command \`${command}\`. ` +
287
+ `Replace \`${command}\`, code ticks included, with ${link}: the CLI prints the command that opens the doc, and doctor checks the link.`,
288
+ });
289
+ }
290
+ }
291
+ }
292
+ return found;
293
+ }