Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(cli): doctor integration components compares documented props with the code (#7676)

Joey01eab6ae7ca4
diff --git a/.changeset/doctor-prop-drift.md b/.changeset/doctor-prop-drift.md
new file mode 100644
index 0000000000..5a690b6b9c
--- /dev/null
+++ b/.changeset/doctor-prop-drift.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] `astryx doctor integration components` compares each component doc's props with the component's TypeScript props, read with the project's own `typescript`. It warns about a documented prop the code does not have, a prop the package declares that the doc leaves out, and a wrong `required`. Without TypeScript it prints one line saying the comparison was skipped; with a TypeScript it cannot read types with (one with no JavaScript compiler API, such as TypeScript 7), that line names the installed version. The findings are warnings, so the exit code does not change; the JSON response gains `data.propDrift`, and nothing else in it changes.
+
+@josephfarina
diff --git a/packages/cli/README.md b/packages/cli/README.md
index e9b9acef6b..7595b2a55c 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -478,7 +478,7 @@ Every response has a `type` discriminant. The full set is below (generated from
| `integration.pack-check` | The packed-package check: name, version, packable, tarball {filename, fileCount, size, unpackedSize} or null, inventory {manifest, roots [{kind, path, expectedFiles, missingFiles, complete}], expectedFiles, packedFiles}, contributions {local, packed}, each null or {themes [{slug, exportName}], components, templates [{id, type, name}], codemods [{version, id}], docs, agentDocsAppend}, and issues [{code, severity, message}]. |
| `integration.validate` | The validation result: validated (false when nothing was validated: with no package.json the issues list carries one no_package error so the command exits 1, and with a package.json but no integration manifest the issues list is empty and proves nothing), the package name and version (both null when validated is false) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning \| error, message}. |
| `integration.template-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking Core template-id conflicts as {id, severity: warning, integrationPackage, integrationType, integrationName, coreMatches, message, command}. |
-| `integration.component-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking conflicts where an integration component name is also owned by Core; each conflict includes the exact package-qualified command. |
+| `integration.component-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking conflicts where an integration component name is also owned by Core; each conflict includes the exact package-qualified command. When the manifest loads and declares a components root, propDrift compares documented props with the TypeScript props: status (checked \| skipped), reason, typescript, components, findings (all warnings), unchecked, and propsNotChecked. |
| `integration.doc-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and Core doc overlaps. Each finding includes `severity` (`info` \| `error`) and `relationship` (`replaces` \| `extends` \| `accidental`). |
<!-- END GENERATED: response-types -->
@@ -551,12 +551,12 @@ data: { checks, summary } }`) that AI agents and scripts can parse.
Omit `[package]` to inspect the package at the current directory, or pass an
installed package name:
-| Command | What it checks | Exit `1` when |
-| ----------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------- |
-| `doctor integration validate [package]` | Manifest shape and every declared contribution | A structural issue has error severity |
-| `doctor integration templates [package]` | Template IDs shared with Core | The integration is invalid; ID conflicts are warnings |
-| `doctor integration components [package]` | Component names shared with Core | The integration is invalid; name conflicts are warnings |
-| `doctor integration docs [package]` | Core topic replacements, extensions, and same-name conflicts | A Core overlap is accidental or the docs are invalid |
+| Command | What it checks | Exit `1` when |
+| ----------------------------------------- | ----------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
+| `doctor integration validate [package]` | Manifest shape and every declared contribution | A structural issue has error severity |
+| `doctor integration templates [package]` | Template IDs shared with Core | The integration is invalid; ID conflicts are warnings |
+| `doctor integration components [package]` | Component names shared with Core, and each props table against the TypeScript props | The integration is invalid; name conflicts and prop differences are warnings |
+| `doctor integration docs [package]` | Core topic replacements, extensions, and same-name conflicts | A Core overlap is accidental or the docs are invalid |
Template and component conflicts include the exact `--package` command needed
to select the integration contribution. Doc replacements and extensions are
diff --git a/packages/cli/api/integration/_adapter.mjs b/packages/cli/api/integration/_adapter.mjs
new file mode 100644
index 0000000000..c054202d61
--- /dev/null
+++ b/packages/cli/api/integration/_adapter.mjs
@@ -0,0 +1,54 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file The integration subject's access to the environment (INV21): reading
+ * one package's component docs and sources with the project's own TypeScript.
+ *
+ * @input a loaded integration and the directory the command runs in
+ * @output the reports the integration checks attach to their results
+ * @position api/integration (internal; not exported from ./api)
+ */
+
+import {
+ discoverValidIntegrationComponents,
+ forEachIntegrationDoc,
+ integrationSourceForDoc,
+} from '../../foundation/discovery/component-discovery.mjs';
+import {comparePropDocs} from '../../foundation/discovery/prop-drift.mjs';
+
+/**
+ * Each component doc's props compared with the component's TypeScript props,
+ * read with the project's own compiler (spec:AST-039 FR12). Without one, the
+ * report says the comparison was skipped.
+ * @param {any} integration a loaded integration
+ * @param {string} cwd
+ * @returns {Promise<import('../../foundation/discovery/prop-drift.mjs').PropDriftReport>}
+ */
+export async function integrationPropDrift(integration, cwd) {
+ const packageDir = /** @type {{__packageDir?: string}} */ (integration)
+ .__packageDir;
+ const {components} = await discoverValidIntegrationComponents(integration);
+ // Every doc the package ships has its prop tables compared or listed as not
+ // compared. A doc discovery leaves out (a hidden one, a second doc for one
+ // name, or one whose source or own file doesn't load) gets a record under
+ // its file name.
+ const recorded = new Set(components.map(c => c.docPath));
+ /** @type {typeof components} */
+ const left = [];
+ forEachIntegrationDoc(integration?.components, (docPath, stem) => {
+ if (recorded.has(docPath)) return;
+ recorded.add(docPath);
+ left.push({
+ name: stem,
+ package: integration.name,
+ docPath,
+ sourcePath: integrationSourceForDoc(docPath),
+ issuesUrl: integration.issuesUrl,
+ group: null,
+ });
+ });
+ return comparePropDocs([...components, ...left], {
+ packageDir: packageDir ?? cwd,
+ resolveFrom: [cwd, packageDir],
+ });
+}
diff --git a/packages/cli/api/integration/authoring-checks.mjs b/packages/cli/api/integration/authoring-checks.mjs
index 66a1222ca5..034ab2827e 100644
--- a/packages/cli/api/integration/authoring-checks.mjs
+++ b/packages/cli/api/integration/authoring-checks.mjs
@@ -3,6 +3,10 @@
/**
* @file Integration authoring diagnostics against the built-in Core catalog.
*
+ * The components check also compares each component doc's props with the
+ * component's TypeScript props (foundation/discovery/prop-drift.mjs); those
+ * findings are warnings under `propDrift`.
+ *
* Templates may intentionally replace Core identities; undeclared same-id
* overlaps stay fail-closed and require package selection. The CLI package
* version gates replacement-specific fields so 0.6.x keeps its released shape.
@@ -25,6 +29,7 @@ import {
discoverOwnedComponents,
} from '../../foundation/discovery/component-discovery.mjs';
import {loadComponentReplacements} from '../component/_adapter.mjs';
+import {integrationPropDrift} from './_adapter.mjs';
import {
discoverBuiltinTopics,
discoverIntegrationDocs,
@@ -242,6 +247,10 @@ export async function integrationComponentConflicts(pkg, options = {}) {
};
}
+ // Each documented prop against the component's TypeScript props, read with
+ // the project's own compiler; without one the report says it was skipped.
+ const propDrift = await integrationPropDrift(resolved.integration, cwd);
+
const coreDir = findCoreDir(cwd);
if (!coreDir) {
issues.push({
@@ -252,7 +261,7 @@ export async function integrationComponentConflicts(pkg, options = {}) {
});
return {
type: 'integration.component-conflicts',
- data: {validated, name, version, conflicts: [], issues},
+ data: {validated, name, version, conflicts: [], issues, propDrift},
};
}
@@ -296,7 +305,7 @@ export async function integrationComponentConflicts(pkg, options = {}) {
return {
type: 'integration.component-conflicts',
- data: {validated, name, version, conflicts, issues},
+ data: {validated, name, version, conflicts, issues, propDrift},
};
}
diff --git a/packages/cli/api/integration/authoring-checks.test.mjs b/packages/cli/api/integration/authoring-checks.test.mjs
index 383ed4d0a1..f240c769d4 100644
--- a/packages/cli/api/integration/authoring-checks.test.mjs
+++ b/packages/cli/api/integration/authoring-checks.test.mjs
@@ -417,6 +417,45 @@ describe('integrationComponentConflicts', () => {
expect(result.data.conflicts).toEqual([]);
expect(result.data.issues).toEqual([]);
});
+
+ it("compares each component doc's props with the component's TypeScript props, as warnings", async () => {
+ writeComponentIntegration('AcmeBadge');
+ fs.writeFileSync(
+ path.join(tmpDir, 'components', 'AcmeBadge.doc.mjs'),
+ `export default {type: 'component', name: 'AcmeBadge', displayName: 'AcmeBadge', description: 'Fixture component.', props: [{name: 'label', type: 'string', description: 'Text.', required: true}, {name: 'size', type: "'sm' | 'md'", description: 'Size.'}]};\n`,
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'components', 'AcmeBadge.tsx'),
+ 'export function AcmeBadge(props: {label: string; count?: number}) { return null; }\n',
+ );
+
+ const result = await integrationComponentConflicts(undefined, {
+ cwd: tmpDir,
+ });
+
+ expect(result.data.issues).toEqual([]);
+ expect(result.data.propDrift).toMatchObject({
+ status: 'checked',
+ components: 1,
+ unchecked: [],
+ });
+ expect(
+ result.data.propDrift?.findings.map(f => [f.prop, f.kind, f.severity]),
+ ).toEqual([
+ ['count', 'not_in_doc', 'warning'],
+ ['size', 'not_in_code', 'warning'],
+ ]);
+ });
+
+ it('leaves propDrift out when the package has no components root', async () => {
+ writeDocIntegration({name: 'acme-setup'});
+
+ const result = await integrationComponentConflicts(undefined, {
+ cwd: tmpDir,
+ });
+
+ expect(result.data).not.toHaveProperty('propDrift');
+ });
});
describe('integrationDocConflicts', () => {
diff --git a/packages/cli/api/integration/authoring-checks.type.mjs b/packages/cli/api/integration/authoring-checks.type.mjs
index 70031f800c..51a61c7dd6 100644
--- a/packages/cli/api/integration/authoring-checks.type.mjs
+++ b/packages/cli/api/integration/authoring-checks.type.mjs
@@ -58,10 +58,23 @@
* @property {{validated: boolean, name: string | null, version: string | null, conflicts: IntegrationTemplateConflict[], issues: import('../../foundation/integrations/issue').AstryxIntegrationIssue[]}} data
*/
+/**
+ * Documented props compared with the component's TypeScript props. Present
+ * when the manifest loads and declares a components root. `status: 'skipped'`
+ * means nothing was compared (no TypeScript in the project) and `reason` says
+ * why. Every finding is a warning.
+ *
+ * @typedef {import('../../foundation/discovery/prop-drift.mjs').PropDriftReport} PropDriftReport
+ */
+
+/**
+ * @typedef {import('../../foundation/discovery/prop-drift.mjs').PropDriftFinding} PropDriftFinding
+ */
+
/**
* @typedef {object} IntegrationComponentConflictResponse
* @property {'integration.component-conflicts'} type
- * @property {{validated: boolean, name: string | null, version: string | null, conflicts: IntegrationComponentConflict[], issues: import('../../foundation/integrations/issue').AstryxIntegrationIssue[]}} data
+ * @property {{validated: boolean, name: string | null, version: string | null, conflicts: IntegrationComponentConflict[], issues: import('../../foundation/integrations/issue').AstryxIntegrationIssue[], propDrift?: PropDriftReport}} data
*/
/**
diff --git a/packages/cli/api/integration/integrationComponentConflicts.doc.mjs b/packages/cli/api/integration/integrationComponentConflicts.doc.mjs
index c8f7beb824..add38b2f98 100644
--- a/packages/cli/api/integration/integrationComponentConflicts.doc.mjs
+++ b/packages/cli/api/integration/integrationComponentConflicts.doc.mjs
@@ -10,17 +10,30 @@ export const doc = {
namespace: 'cli/api',
displayName: 'integrationComponentConflicts()',
summary:
- 'Check integration component names and replaces declarations against Core.',
+ 'Check integration component names, replaces declarations, and documented props.',
description:
'Loads one local or installed integration, compares its component names with ' +
'Core, and returns non-blocking conflicts with the exact package-qualified ' +
"component command required to keep an intentional overlap. Each component's " +
'replaces is checked too: its findings are issues, errors for a package that ' +
- 'declares the CLI range that turns replacement on and warnings otherwise.',
+ 'declares the CLI range that turns replacement on and warnings otherwise. ' +
+ "Each component doc's props are compared with the component's TypeScript props, " +
+ "read with the project's own `typescript`: a documented prop the code lacks, a " +
+ 'prop the package declares that the doc omits, or a wrong `required`. Those ' +
+ 'findings are warnings ' +
+ 'in `propDrift`; without TypeScript it is `skipped` with a reason.',
importPath: '@astryxdesign/cli/api',
signature:
'integrationComponentConflicts(pkg?: string, options?: IntegrationAuthoringOptions): Promise<IntegrationComponentConflictResponse>',
- keywords: ['integration', 'component', 'conflict', 'authoring', 'doctor'],
+ keywords: [
+ 'integration',
+ 'component',
+ 'conflict',
+ 'authoring',
+ 'doctor',
+ 'props',
+ 'drift',
+ ],
params: [
{name: 'pkg', type: 'string', description: 'Installed package; omit for the local package.'},
{name: 'options.cwd', type: 'string', description: 'Resolution directory.'},
@@ -29,11 +42,14 @@ export const doc = {
{
type: 'integration.component-conflicts',
description:
- '`validated` (false when no integration manifest was found, so nothing was inspected), integration identity, structural and replaces issues, and Core component-name conflicts with package-qualified commands. An active replacement that keeps the Core name it replaces is not a conflict.',
+ '`validated` (false when no integration manifest was found, so nothing was inspected), integration identity, structural and replaces issues, and Core component-name conflicts with package-qualified commands. An active replacement that keeps the Core name it replaces is not a conflict. When the manifest loads and declares a components root, `propDrift` holds the props comparison: `status` (`checked` | `skipped`), `reason` when skipped, `typescript`, `components` compared, `findings` ({component, prop, kind: `not_in_code` | `not_in_doc` | `required_mismatch`, severity: `warning`, message, doc, source, docType?, codeType?, docRequired?, codeRequired?}), `unchecked` ({component, doc, reason}), and `propsNotChecked` when a mapped type builds props from keys the check cannot trace to the package ({component, doc, reason, props}: no warning is drawn for those props).',
},
],
examples: [
- {label: 'Check the local integration', code: 'await integrationComponentConflicts();'},
+ {
+ label: 'Check the local integration',
+ code: 'await integrationComponentConflicts();',
+ },
],
command: 'doctor integration components',
related: ['integrationTemplateConflicts', 'component'],
diff --git a/packages/cli/assets/docs/tree/check-the-props.doc.mjs b/packages/cli/assets/docs/tree/check-the-props.doc.mjs
new file mode 100644
index 0000000000..eba3f81922
--- /dev/null
+++ b/packages/cli/assets/docs/tree/check-the-props.doc.mjs
@@ -0,0 +1,145 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `astryx docs cli/integrations/building-blocks/components/describe-the-component/check-the-props`:
+ * compare each component doc's props table with the component's TypeScript
+ * props, read each finding, and fix the doc or the code.
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */
+export const docs = {
+ type: 'generic',
+ name: 'check-the-props',
+ placement: {
+ parent: 'namespace:describe-the-component',
+ slot: 'guides',
+ order: 50,
+ },
+ title: 'Check the props table',
+ category: 'guide',
+ keywords: [
+ 'props table',
+ 'documented props',
+ 'prop drift',
+ 'props not compared',
+ ],
+ description:
+ "Compare each props table with the component's TypeScript props, then fix the doc or the code.",
+ sections: [
+ {
+ id: 'run-the-props-check',
+ title: 'Run the props check',
+ content: [
+ {
+ type: 'prose',
+ text: "`doctor integration components` compares every props table in your component docs, hidden docs and every family entry included, with the props the component's TypeScript declares. Run it in your package after you change a component or its doc.",
+ },
+ {
+ type: 'code',
+ lang: 'bash',
+ code: 'npx astryx doctor integration components',
+ },
+ {
+ type: 'code',
+ lang: 'text',
+ code: `severity: [warn]
+component: AcmeCarousel
+prop: loop
+kind: not_in_code
+message: "loop" is documented, but AcmeCarousel's props have no "loop".
+doc: components/AcmeCarousel.doc.mjs
+source: components/AcmeCarousel.tsx
+docType: boolean
+
+1 prop(s) differ between the docs and the code in 1 of 1 component(s) compared (TypeScript 6.0.3). These are warnings: update the doc, or the code if the doc is right.`,
+ },
+ {
+ type: 'list',
+ style: 'unordered',
+ items: [
+ "A doc's own `props` describe the export its `name` names. In a family doc, each entry describes its own export. A hook entry documents parameters and returns, so it is not compared.",
+ "It reads props with the `typescript` your package installs, and reads your package's `tsconfig.json` the way `tsc -p` does. Without TypeScript it prints `[skip] Props not compared` and the reason.",
+ 'Every finding is a warning, so the exit code stays 0. Read them before you publish. With `--json`, they are in `data.propDrift.findings`.',
+ ],
+ },
+ ],
+ },
+ {
+ id: 'fix-each-finding',
+ title: 'Fix each finding',
+ content: [
+ {
+ type: 'prose',
+ text: "Each finding's `kind` says what differs. Fix the doc, or the code if the doc is right.",
+ },
+ {
+ type: 'table',
+ headers: ['Kind', 'Means', 'Fix'],
+ rows: [
+ [
+ '`not_in_code`',
+ "The doc lists a prop the component's props do not have",
+ 'Remove it from the doc, or add it to the code. A name an index signature takes, such as `data-*`, counts as present',
+ ],
+ [
+ '`not_in_doc`',
+ "Your package declares a prop the doc does not list, or builds one with a mapped type, such as `Partial<Record<'sm' | 'md', string>>`",
+ 'Document it. Props from React, the DOM, or another package are never asked for, and neither are props whose keys another package defines (`keyof CSSProperties`, behind an alias or not), `className`, `style`, `xstyle`, `data-testid`, `ref`, `key`, or a prop whose JSDoc has `@internal`. A deprecated prop is still a prop: document it until you remove it. A prop a mapped type builds from keys the check cannot trace (a template literal, say) is listed under `[info] Props not checked for a doc entry` instead',
+ ],
+ [
+ '`required_mismatch`',
+ '`required` disagrees with the code',
+ 'Set `required: true` exactly when every caller must pass the prop. One your `defaultProps` fills counts as optional, as it is to JSX callers, and so does one only some members of a union require, since a caller can leave it out: say in its description which variants need it. An entry that names several props (`value / onChange`) makes the same claim about each: give them separate entries when they differ',
+ ],
+ ],
+ },
+ ],
+ },
+ {
+ id: 'when-a-component-is-not-compared',
+ title: 'When a component is not compared',
+ content: [
+ {
+ type: 'prose',
+ text: "When the check cannot read a component's props exactly, it lists the component under `[info] Props not compared`, with the reason, instead of reporting findings that might be wrong.",
+ },
+ {
+ type: 'code',
+ lang: 'text',
+ code: `[info] Props not compared for 1 documented component(s):
+
+component: AcmeCarousel
+doc: components/AcmeCarousel.doc.mjs
+reason: AcmeCarousel depends on \`@acme/motion\` (imported in AcmeCarousel.tsx), which the compiler could not resolve, usually a dependency that is not installed. Install the package's dependencies and run this check again`,
+ },
+ {
+ type: 'table',
+ headers: ['Reason', 'Fix'],
+ rows: [
+ [
+ 'It depends on a package or file the compiler could not resolve',
+ "Install the package's dependencies, then run the check again",
+ ],
+ [
+ "It depends on a type the compiler can't work out",
+ 'Make the types compile with `npx tsc --noEmit`, then run the check again',
+ ],
+ [
+ "The package's TypeScript config has an error",
+ 'Fix `tsconfig.json` until `npx tsc -p .` reads it',
+ ],
+ ['Its props are typed `any`', 'Give the component a props type'],
+ [
+ 'Some prop names come from a type parameter',
+ 'Nothing to fix: a component that renders an element the caller picks takes props known only where it is used',
+ ],
+ [
+ "The file has no export named by the doc's `name`",
+ 'Change `name` or the export so they agree',
+ ],
+ ],
+ },
+ ],
+ },
+ ],
+};
diff --git a/packages/cli/assets/docs/tree/checks.doc.mjs b/packages/cli/assets/docs/tree/checks.doc.mjs
index 91bb2905d0..4e89188c0d 100644
--- a/packages/cli/assets/docs/tree/checks.doc.mjs
+++ b/packages/cli/assets/docs/tree/checks.doc.mjs
@@ -36,9 +36,9 @@ export const docs = {
],
[
'`npx astryx doctor integration components`',
- 'No component name clashes with a Core component, and each `replaces` names one Core component',
+ "No component name clashes with a Core component, each `replaces` names one Core component, and each component doc's props match the component's TypeScript props",
'Core is not installed (`core_not_found`). In a package that declares the CLI range that turns replacement on, a `replaces` target is missing (`missing_component_replacement_target`) or invalid (`invalid_component_replacement`), or two components replace one Core component (`ambiguous_component_replacement`)',
- 'A name clashes with Core, or a component sets `replaces` in a package without that range (`inactive_component_replacement`, plus any missing, invalid, or duplicate `replaces` reported as a warning)',
+ 'A name clashes with Core, a component sets `replaces` in a package without that range (`inactive_component_replacement`, plus any missing, invalid, or duplicate `replaces` reported as a warning), or a documented prop differs from the code: it is missing there (`not_in_code`), the doc omits a prop the package declares (`not_in_doc`), or its `required` disagrees (`required_mismatch`). It reads props with your installed `typescript`; without it, it prints `[skip] Props not compared`',
],
[
'`npx astryx doctor integration templates`',
@@ -62,7 +62,7 @@ export const docs = {
},
{
type: 'prose',
- text: 'Pass a package name, such as `npx astryx doctor integration validate @acme/astryx-widgets`, to check an installed copy from an app instead.',
+ text: 'Pass a package name, such as `npx astryx doctor integration validate @acme/astryx-widgets`, to check an installed copy from an app instead. To fix a props finding, see {@link generic:check-the-props}.',
},
],
},
diff --git a/packages/cli/assets/docs/tree/describe-the-component.doc.mjs b/packages/cli/assets/docs/tree/describe-the-component.doc.mjs
index 7ea18f6254..802eb728fe 100644
--- a/packages/cli/assets/docs/tree/describe-the-component.doc.mjs
+++ b/packages/cli/assets/docs/tree/describe-the-component.doc.mjs
@@ -37,7 +37,7 @@ export const docs = {
items: [
'Change the source and its `.doc.mjs` together.',
'Update the doc whenever the public name, import, behavior, props, defaults, examples, or accessibility requirements change.',
- '`integration verify` checks the doc shape and packed import, but it cannot prove the prose still matches the component.',
+ '`integration verify` checks the doc shape and packed import, and `doctor integration components` compares each props table with the component\'s TypeScript props ({@link generic:check-the-props}). Neither can prove the prose still matches the component.',
],
},
{
diff --git a/packages/cli/assets/docs/tree/single-component.doc.mjs b/packages/cli/assets/docs/tree/single-component.doc.mjs
index 27acdcef38..49c125aaf2 100644
--- a/packages/cli/assets/docs/tree/single-component.doc.mjs
+++ b/packages/cli/assets/docs/tree/single-component.doc.mjs
@@ -122,6 +122,7 @@ export default {
'Set `required: true` only when every caller must pass the prop.',
'Write `default` exactly as the value should appear in documentation.',
'Skip styling escape hatches such as `xstyle`, `className`, and `style`.',
+ '`npx astryx doctor integration components` lists a documented prop the code lacks, a public prop the doc misses, and a wrong `required`. See {@link generic:check-the-props}.',
],
},
],
@@ -157,7 +158,7 @@ export default {
{
type: 'code',
lang: 'bash',
- code: 'npx astryx component AcmeCarousel\nnpx astryx integration verify',
+ code: 'npx astryx component AcmeCarousel\nnpx astryx doctor integration components\nnpx astryx integration verify',
},
],
},
diff --git a/packages/cli/clients/cli/commands/doctor-integration-components.doc.mjs b/packages/cli/clients/cli/commands/doctor-integration-components.doc.mjs
index 6a3cfd621e..f80dd88ab8 100644
--- a/packages/cli/clients/cli/commands/doctor-integration-components.doc.mjs
+++ b/packages/cli/clients/cli/commands/doctor-integration-components.doc.mjs
@@ -8,7 +8,8 @@ export const doc = {
name: 'doctor integration components',
displayName: 'astryx doctor integration components',
namespace: 'cli/commands',
- summary: 'Check integration component names and replacements against Core',
+ summary:
+ 'Check integration component names, replacements, and documented props',
description:
'Compares one local or installed integration with Core component names. A ' +
'conflict is allowed and exits successfully, but the report recommends ' +
@@ -17,7 +18,12 @@ export const doc = {
'range that turns replacement on, a missing Core target, an invalid value, a ' +
'component named after a different Core component, or two replacements for one ' +
'Core component is an error. In a package without that range they are warnings, ' +
- 'with a warning for each such component, naming the range to declare.',
+ 'with a warning for each such component, naming the range to declare. ' +
+ "Then it compares each component doc's props with the component's TypeScript " +
+ "props, using the project's own `typescript`, and warns about a documented prop " +
+ 'the code lacks, a prop the package declares that the doc omits, and a wrong ' +
+ '`required`. Without TypeScript it prints one ' +
+ 'line saying the comparison was skipped.',
fn: 'integrationComponentConflicts',
args: [
{
@@ -38,7 +44,7 @@ export const doc = {
exitCodes: [
{
code: 0,
- when: 'the check completed; component name conflicts, and replaces findings for a package without the CLI range, are warnings',
+ when: 'the check completed; component name conflicts, replaces findings for a package without the CLI range, and props that differ from the code are warnings',
},
{
code: 1,
diff --git a/packages/cli/clients/cli/commands/doctor-integration.test.mjs b/packages/cli/clients/cli/commands/doctor-integration.test.mjs
index 2d7d2b3e39..0939f23d61 100644
--- a/packages/cli/clients/cli/commands/doctor-integration.test.mjs
+++ b/packages/cli/clients/cli/commands/doctor-integration.test.mjs
@@ -21,6 +21,7 @@ import {discoverOwnedComponents} from '../../../foundation/discovery/component-d
import {discoverBuiltinTopics} from '../../../foundation/discovery/docs-discovery.mjs';
import {findCoreDir} from '../../../foundation/fs/paths.mjs';
import {registerDoctor} from './doctor.mjs';
+import {expectRecordsCarry} from '../../../test-utils/text-projection.mjs';
let tmpDir;
let previousCwd;
@@ -366,6 +367,10 @@ describe('doctor integration — command', () => {
const printed = logCalls.join('\n');
expect(printed).toContain('core_not_found');
expect(printed).not.toContain('[ok]');
+ // No TypeScript out here either: the props comparison says it skipped.
+ expect(printed).toContain(
+ '[skip] Props not compared: TypeScript is not installed in this project',
+ );
expect(process.exitCode).toBe(1);
} finally {
tmpDir = previousTmp;
@@ -396,6 +401,328 @@ describe('doctor integration — command', () => {
expect(process.exitCode).toBeUndefined();
});
+ it('components prints each documented prop that differs from the code, and still exits 0', async () => {
+ writeComponentIntegration('AcmeBadge');
+ fs.writeFileSync(
+ path.join(tmpDir, 'components', 'AcmeBadge.doc.mjs'),
+ `export default {type: 'component', name: 'AcmeBadge', displayName: 'AcmeBadge', description: 'Fixture component.', props: [{name: 'label', type: 'string', description: 'Text.'}]};\n`,
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'components', 'AcmeBadge.tsx'),
+ 'export function AcmeBadge(props: {label: string}) { return null; }\n',
+ );
+ process.chdir(tmpDir);
+
+ await createProgram().parseAsync([
+ 'node',
+ 'astryx',
+ 'doctor',
+ 'integration',
+ 'components',
+ ]);
+
+ const output = logCalls.join('\n');
+ expect(output).toMatch(/^kind:\s+required_mismatch$/m);
+ expect(output).toContain(
+ '"label" is required in the code, but the doc does not mark it required.',
+ );
+ expect(output).toContain(
+ '1 prop(s) differ between the docs and the code in 1 of 1 component(s) compared (TypeScript',
+ );
+ expect(output).not.toContain('[ok] Documented prop');
+ expect(process.exitCode).toBeUndefined();
+ });
+
+ it('components compares a hidden doc and a family entry with no record, so their drift is never an [ok]', async () => {
+ writeComponentIntegration('AcmeMenu');
+ const dir = path.join(tmpDir, 'components');
+ fs.writeFileSync(
+ path.join(dir, 'AcmeMenu.doc.mjs'),
+ `export default {type: 'component', name: 'AcmeMenuRoot', displayName: 'AcmeMenuRoot', description: 'Fixture component.', hiddenComponents: ['AcmeMenuItem'], components: [{name: 'AcmeMenuItem', displayName: 'AcmeMenuItem', description: 'Fixture item.', props: [{name: 'label', type: 'string', description: 'Text.'}]}]};\n`,
+ );
+ fs.writeFileSync(
+ path.join(dir, 'AcmeMenu.tsx'),
+ 'export function AcmeMenuRoot() { return null; }\nexport function AcmeMenuItem(props: {value?: string}) { return null; }\n',
+ );
+ fs.writeFileSync(
+ path.join(dir, 'AcmeSecret.doc.mjs'),
+ `export default {type: 'component', name: 'AcmeSecret', displayName: 'AcmeSecret', description: 'Fixture component.', hidden: true, props: [{name: 'tone', type: 'string', description: 'Tone.'}]};\n`,
+ );
+ fs.writeFileSync(
+ path.join(dir, 'AcmeSecret.tsx'),
+ 'export function AcmeSecret(props: {size?: number}) { return null; }\n',
+ );
+ process.chdir(tmpDir);
+ const run = async (/** @type {string[]} */ flags) => {
+ logCalls.length = 0;
+ await createProgram().parseAsync([
+ 'node',
+ 'astryx',
+ ...flags,
+ 'doctor',
+ 'integration',
+ 'components',
+ ]);
+ return logCalls.join('\n');
+ };
+
+ const report = JSON.parse(await run(['--json'])).data.propDrift;
+ const output = await run([]);
+
+ expect(
+ report.findings.map(f => `${f.component}.${f.prop} ${f.kind}`),
+ ).toEqual([
+ 'AcmeMenuItem.label not_in_code',
+ 'AcmeMenuItem.value not_in_doc',
+ 'AcmeSecret.size not_in_doc',
+ 'AcmeSecret.tone not_in_code',
+ ]);
+ expect(output).not.toContain('[ok] Documented prop');
+ expect(process.exitCode).toBeUndefined();
+ });
+
+ it('components lists props a mapped type builds from keys it cannot trace, and says the [ok] leaves them out', async () => {
+ writeComponentIntegration('AcmeChip');
+ const dir = path.join(tmpDir, 'components');
+ fs.writeFileSync(
+ path.join(dir, 'AcmeChip.doc.mjs'),
+ `export default {type: 'component', name: 'AcmeChip', displayName: 'AcmeChip', description: 'Fixture.', props: [{name: 'label', type: 'string', description: 'Text.'}]};\n`,
+ );
+ fs.writeFileSync(
+ path.join(dir, 'AcmeChip.tsx'),
+ "export function AcmeChip(props: {label?: string} & {[K in `on${Capitalize<'open'>}`]?: () => void}) { return null; }\n",
+ );
+ process.chdir(tmpDir);
+ const run = async (/** @type {string[]} */ flags) => {
+ logCalls.length = 0;
+ await createProgram().parseAsync([
+ 'node',
+ 'astryx',
+ ...flags,
+ 'doctor',
+ 'integration',
+ 'components',
+ ]);
+ return logCalls.join('\n');
+ };
+
+ const {propsNotChecked} = JSON.parse(await run(['--json'])).data.propDrift;
+ const output = await run([]);
+
+ expect(propsNotChecked).toEqual([
+ expect.objectContaining({component: 'AcmeChip', props: ['onOpen']}),
+ ]);
+ expect(output).toContain(
+ '[info] Props not checked for a doc entry in 1 component(s):',
+ );
+ expect(output).toContain(
+ 'in 1 component(s), apart from the props not checked (TypeScript',
+ );
+ });
+
+ it('components compares the entries of a family doc whose own source is missing', async () => {
+ writeComponentIntegration('AcmeTabs');
+ const dir = path.join(tmpDir, 'components');
+ const entry = (/** @type {string} */ name, /** @type {string} */ prop) =>
+ `{name: '${name}', displayName: '${name}', description: 'Fixture.', props: [{name: '${prop}', type: 'string', description: 'Text.'}]}`;
+ fs.writeFileSync(
+ path.join(dir, 'AcmeTabs.doc.mjs'),
+ `export default {type: 'component', name: 'AcmeTabs', displayName: 'AcmeTabs', description: 'Fixture.', props: [], hiddenComponents: ['AcmeTabsPanel'], components: [${entry('AcmeTabsItem', 'label')}, ${entry('AcmeTabsPanel', 'ghost')}]};\n`,
+ );
+ fs.rmSync(path.join(dir, 'AcmeTabs.tsx'), {force: true});
+ // The package's entry exports the members, so discovery records the
+ // listed one, though the family's own file is missing.
+ for (const name of ['AcmeTabsItem', 'AcmeTabsPanel']) {
+ fs.writeFileSync(
+ path.join(dir, `${name}.tsx`),
+ `export function ${name}(props: {label?: string; open?: boolean}) { return null; }\n`,
+ );
+ fs.appendFileSync(
+ path.join(tmpDir, 'index.ts'),
+ `export {${name}} from './components/${name}';\n`,
+ );
+ }
+ process.chdir(tmpDir);
+
+ await createProgram().parseAsync([
+ 'node',
+ 'astryx',
+ '--json',
+ 'doctor',
+ 'integration',
+ 'components',
+ ]);
+ const report = JSON.parse(logCalls.join('\n')).data.propDrift;
+
+ expect(
+ report.findings.map(
+ (/** @type {any} */ f) => `${f.component}.${f.prop} ${f.kind}`,
+ ),
+ ).toEqual([
+ 'AcmeTabsItem.open not_in_doc',
+ 'AcmeTabsPanel.ghost not_in_code',
+ 'AcmeTabsPanel.label not_in_doc',
+ 'AcmeTabsPanel.open not_in_doc',
+ ]);
+ expect(report.unchecked).toEqual([
+ {
+ component: 'AcmeTabs',
+ doc: 'components/AcmeTabs.doc.mjs',
+ reason: 'no source file for AcmeTabs',
+ },
+ ]);
+ });
+
+ it('components counts two docs of one name as two components, and compares a .doc.ts beside a .doc.mjs', async () => {
+ writeComponentIntegration('AcmeTwin');
+ const dir = path.join(tmpDir, 'components');
+ const doc = (/** @type {string} */ name, /** @type {string} */ prop) =>
+ `export default {type: 'component', name: '${name}', displayName: '${name}', description: 'Fixture.', props: [{name: '${prop}', type: 'string', description: 'Text.'}]};\n`;
+ fs.writeFileSync(
+ path.join(dir, 'AcmeTwin.doc.mjs'),
+ doc('AcmeTwin', 'tone'),
+ );
+ fs.writeFileSync(
+ path.join(dir, 'AcmeTwin.doc.ts'),
+ doc('AcmeTwin', 'size'),
+ );
+ fs.writeFileSync(
+ path.join(dir, 'AcmeTwin.tsx'),
+ 'export function AcmeTwin(props: {label?: string}) { return null; }\n',
+ );
+ for (const folder of ['a', 'b']) {
+ fs.mkdirSync(path.join(dir, folder));
+ fs.writeFileSync(
+ path.join(dir, folder, 'AcmeX.doc.mjs'),
+ doc('AcmeX', folder),
+ );
+ fs.writeFileSync(
+ path.join(dir, folder, 'AcmeX.tsx'),
+ 'export function AcmeX() { return null; }\n',
+ );
+ }
+ process.chdir(tmpDir);
+ const run = async (/** @type {string[]} */ flags) => {
+ logCalls.length = 0;
+ await createProgram().parseAsync([
+ 'node',
+ 'astryx',
+ ...flags,
+ 'doctor',
+ 'integration',
+ 'components',
+ ]);
+ return logCalls.join('\n');
+ };
+
+ const report = JSON.parse(await run(['--json'])).data.propDrift;
+ const output = await run([]);
+
+ expect(
+ report.findings
+ .filter(f => f.kind === 'not_in_code')
+ .map(f => `${f.doc} ${f.prop}`)
+ .sort(),
+ ).toEqual([
+ 'components/AcmeTwin.doc.mjs tone',
+ 'components/AcmeTwin.doc.ts size',
+ 'components/a/AcmeX.doc.mjs a',
+ 'components/b/AcmeX.doc.mjs b',
+ ]);
+ expect(output).toMatch(/ in 4 of 4 component\(s\) compared /);
+ });
+
+ it('components prints every field of the props comparison that JSON carries', async () => {
+ writeComponentIntegration('AcmeBadge');
+ fs.writeFileSync(
+ path.join(tmpDir, 'components', 'AcmeBadge.doc.mjs'),
+ `export default {type: 'component', name: 'AcmeBadge', displayName: 'AcmeBadge', description: 'Fixture component.', props: [${[
+ "{name: 'label', type: 'string', description: 'Text.'}",
+ "{name: 'elevation', type: 'number', description: 'Shadow.'}",
+ ].join(', ')}]};\n`,
+ );
+ // `key` is a prop a doc never needs, though the component declares it.
+ fs.writeFileSync(
+ path.join(tmpDir, 'components', 'AcmeBadge.tsx'),
+ "export function AcmeBadge(props: {label: string; tone?: 'neutral' | 'info'; key?: string}) { return null; }\n",
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'components', 'AcmeLonely.doc.mjs'),
+ `export default {type: 'component', name: 'AcmeLonely', displayName: 'AcmeLonely', description: 'Fixture component.', props: []};\n`,
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'components', 'AcmeLonely.tsx'),
+ 'export function Other() { return null; }\n',
+ );
+ process.chdir(tmpDir);
+ const run = async (/** @type {string[]} */ flags) => {
+ logCalls.length = 0;
+ await createProgram().parseAsync([
+ 'node',
+ 'astryx',
+ ...flags,
+ 'doctor',
+ 'integration',
+ 'components',
+ ]);
+ return logCalls.join('\n');
+ };
+
+ const report = JSON.parse(await run(['--json'])).data.propDrift;
+ const output = await run([]);
+
+ expect(report.findings.map(f => `${f.prop} ${f.kind}`)).toEqual([
+ 'elevation not_in_code',
+ 'label required_mismatch',
+ 'tone not_in_doc',
+ ]);
+ expectRecordsCarry(output, report.findings, ['component', 'prop', 'kind']);
+ expectRecordsCarry(output, report.unchecked, ['component', 'reason']);
+ expect(output).toContain(
+ `in 1 of ${report.components} component(s) compared (TypeScript ${report.typescript}).`,
+ );
+ });
+
+ it('components says documented props match when they do', async () => {
+ writeComponentIntegration('AcmeOnlyWidget');
+ process.chdir(tmpDir);
+
+ await createProgram().parseAsync([
+ 'node',
+ 'astryx',
+ 'doctor',
+ 'integration',
+ 'components',
+ ]);
+
+ expect(logCalls.join('\n')).toMatch(
+ /\[ok\] Documented prop names and required flags match the code in 1 component\(s\) \(TypeScript \d/,
+ );
+ });
+
+ it('components prints no [ok] for props it could not compare', async () => {
+ writeComponentIntegration('AcmeLonely');
+ fs.writeFileSync(
+ path.join(tmpDir, 'components', 'AcmeLonely.tsx'),
+ 'export function Other() { return null; }\n',
+ );
+ process.chdir(tmpDir);
+
+ await createProgram().parseAsync([
+ 'node',
+ 'astryx',
+ 'doctor',
+ 'integration',
+ 'components',
+ ]);
+
+ const output = logCalls.join('\n');
+ expect(output).toContain(
+ '[info] Props not compared for 1 documented component(s):',
+ );
+ expect(output).not.toContain('[ok] Documented prop');
+ });
+
it('components exposes conflicts as structured JSON warnings', async () => {
const coreDir = findCoreDir(tmpDir);
expect(coreDir).not.toBeNull();
diff --git a/packages/cli/clients/cli/commands/doctor.mjs b/packages/cli/clients/cli/commands/doctor.mjs
index 46db659ad6..b23ac37b72 100644
--- a/packages/cli/clients/cli/commands/doctor.mjs
+++ b/packages/cli/clients/cli/commands/doctor.mjs
@@ -173,6 +173,79 @@ function printTemplateConflicts(data) {
emit(...output);
}
+/**
+ * The documented-props comparison, with every field its JSON carries: a
+ * visible line when it was skipped, the findings (all warnings), the
+ * components it could not read, and how many were compared with which
+ * TypeScript, as an [ok] when nothing differs (never after a failed check).
+ * @param {import('../../../api/integration/authoring-checks.type.mjs').PropDriftReport | undefined} report
+ * @param {boolean} failed
+ */
+function propDriftBlocks(report, failed) {
+ if (!report) return [];
+ if (report.status === 'skipped') {
+ return [text(`[skip] Props not compared: ${report.reason}`)];
+ }
+ const blocks = [];
+ if (report.findings.length > 0) {
+ // Two docs of one name are two components.
+ const components = new Set(
+ report.findings.map(f => `${f.doc}\0${f.component}`),
+ ).size;
+ blocks.push(
+ records(report.findings, {
+ fields: [
+ 'severity',
+ 'component',
+ 'prop',
+ 'kind',
+ 'message',
+ 'doc',
+ 'source',
+ 'docType',
+ 'codeType',
+ 'docRequired',
+ 'codeRequired',
+ ],
+ format: {severity: statusToken},
+ }),
+ text(
+ `${report.findings.length} prop(s) differ between the docs and the code in ${components} of ${report.components} component(s) compared (TypeScript ${report.typescript}). ` +
+ 'These are warnings: update the doc, or the code if the doc is right.',
+ ),
+ );
+ }
+ if (report.unchecked.length > 0) {
+ blocks.push(
+ text(
+ `[info] Props not compared for ${report.unchecked.length} documented component(s):`,
+ ),
+ records(report.unchecked, {fields: ['component', 'doc', 'reason']}),
+ );
+ }
+ const notChecked = report.propsNotChecked ?? [];
+ if (notChecked.length > 0) {
+ blocks.push(
+ text(
+ `[info] Props not checked for a doc entry in ${notChecked.length} component(s):`,
+ ),
+ records(notChecked, {fields: ['component', 'doc', 'reason', 'props']}),
+ );
+ }
+ if (report.findings.length === 0) {
+ const apart =
+ notChecked.length > 0 ? ', apart from the props not checked' : '';
+ blocks.push(
+ text(
+ !failed && report.components > 0
+ ? `[ok] Documented prop names and required flags match the code in ${report.components} component(s)${apart} (TypeScript ${report.typescript}).`
+ : `[info] Props compared in ${report.components} component(s) (TypeScript ${report.typescript}).`,
+ ),
+ );
+ }
+ return blocks;
+}
+
/**
* @param {import('../../../api/integration/authoring-checks.type.mjs').IntegrationComponentConflictResponse['data']} data
*/
@@ -205,6 +278,7 @@ function printComponentConflicts(data) {
),
);
}
+ output.push(...propDriftBlocks(data.propDrift, failed));
emit(...output);
}
diff --git a/packages/cli/foundation/discovery/component-discovery.mjs b/packages/cli/foundation/discovery/component-discovery.mjs
index 7b0729a364..47f53f5a0a 100644
--- a/packages/cli/foundation/discovery/component-discovery.mjs
+++ b/packages/cli/foundation/discovery/component-discovery.mjs
@@ -1047,7 +1047,7 @@ function isWithin(folder, file) {
* @param {string} name
* @returns {string | null}
*/
-function folderSourceFor(folder, name) {
+export function folderSourceFor(folder, name) {
/** @type {string[]} */
const files = [];
/** @param {string} dirPath */
@@ -1242,7 +1242,7 @@ export function forEachIntegrationDoc(componentsDir, visit) {
* @param {string} docPath absolute path to a `{Name}.doc.{ts,mjs,js}` file
* @returns {string|null}
*/
-function integrationSourceForDoc(docPath) {
+export function integrationSourceForDoc(docPath) {
const dir = path.dirname(docPath);
const base = path.basename(docPath).replace(/\.doc\.(ts|mjs|js)$/, '');
const candidate = path.join(dir, `${base}.tsx`);
diff --git a/packages/cli/foundation/discovery/prop-drift.mjs b/packages/cli/foundation/discovery/prop-drift.mjs
index 1c7b52d305..07ae713f28 100644
--- a/packages/cli/foundation/discovery/prop-drift.mjs
+++ b/packages/cli/foundation/discovery/prop-drift.mjs
@@ -7,6 +7,12 @@
* The compiler is the project's own `typescript`. Without one it can use, the
* comparison is skipped and says why. Every finding is a warning.
*
+ * `comparePropDocs` finds each component doc's prop tables first: a doc's
+ * own `props` document the export its `name` names; each entry of a
+ * multi-component doc documents its own export, which a member record
+ * compares against its own source. Hook entries (`use…`) document parameters
+ * and returns, not props, and are not compared.
+ *
* Each table (a doc's `props`, or a multi-component doc's entry, with the
* export it documents and the files that may hold it) is compared with that
* export's props type:
@@ -24,15 +30,17 @@
* callers; an entry that names several props claims its `required` for
* each).
*
- * @input Prop tables, the package root, and the directories to resolve
- * `typescript` from.
+ * @input Component records (name, docPath, sourcePath), or prop tables, the
+ * package root, and the directories to resolve `typescript` from.
* @output A PropDriftReport.
- * @position Foundation discovery: it reads the package's TypeScript and
- * returns a report, and prints nothing itself.
+ * @position Shared by `astryx doctor integration components` and the Astryx
+ * repository's test over Core's own component docs.
*/
import * as fs from 'node:fs';
import * as path from 'node:path';
+import {folderSourceFor} from './component-discovery.mjs';
+import {loadComponentDoc} from './component-loader.mjs';
import {readPackageTsconfig} from './package-tsconfig.mjs';
import {
resolveProjectTypeScript,
@@ -56,6 +64,10 @@ import {
* @property {string} message
* @property {string} doc the doc file, relative to the package root
* @property {string} source the source file, relative to the package root
+ * @property {string} [docType] the documented type, as written
+ * @property {string} [codeType] the type as the source declares it
+ * @property {boolean} [docRequired]
+ * @property {boolean} [codeRequired]
*/
/**
@@ -88,6 +100,15 @@ import {
* @property {string[]} sources the files that may hold the export, in order
*/
+/**
+ * @typedef {object} PropDriftComponent
+ * @property {string} name
+ * @property {string} docPath absolute path to the component's `.doc.*` file
+ * @property {string | null} sourcePath absolute path to its same-stem
+ * source, or null when no file in the package declares it (a family member
+ * only another folder or built output defines)
+ */
+
/**
* Props a doc never needs to list: the internal and styling props the
* `ComponentPropDoc` authoring guidance says to skip, `ref`, which Core's
@@ -104,11 +125,26 @@ export const PROPS_NOT_DOCUMENTED = Object.freeze([
/** The guidance's internal props: a declaration tagged `@internal`. */
const SKIP_TAGS = new Set(['internal']);
+const HOOK_NAME = /^use[A-Z0-9]/;
/** The line both surfaces print when the compiler is missing. */
export const TYPESCRIPT_MISSING_REASON =
'TypeScript is not installed in this project, so documented props were not compared with the code. Install typescript and run this check again.';
+/**
+ * @template T
+ * @param {() => T} compute
+ * @returns {() => T}
+ */
+function memo(compute) {
+ /** @type {{value: T} | null} */
+ let cached = null;
+ return () => {
+ if (cached == null) cached = {value: compute()};
+ return cached.value;
+ };
+}
+
/** @type {WeakMap<Function, (file: string) => boolean>} */
const MINE = new WeakMap();
@@ -164,6 +200,8 @@ function ownFileTest(root) {
* from keys it writes
* @property {boolean} [untraced] built from keys the check can't trace
* @property {boolean} skipTagged its declaration carries an internal JSDoc tag
+ * @property {string[]} declared the type as written, per own declaration
+ * @property {() => string[]} renderings the compiler's renderings, computed on demand
* @property {() => any[]} types the prop's type in each member of the props type
*/
@@ -340,6 +378,14 @@ function readCodeProps(
reason: `${exportName}'s props take some of their names from a type parameter, such as the element it renders, so which props it accepts is known only where it is used`,
};
}
+ // Each member of a prop's type is printed on its own, and long prints are
+ // truncated: a type that expands to a huge structure (StyleX styles, say)
+ // never matches a documented type anyway, and printing it whole can take
+ // gigabytes.
+ const flags =
+ ts.TypeFormatFlags.UseSingleQuotesForStringLiteralType |
+ ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope;
+
// `defaultProps` the package sets (a class's static field, one assigned to a
// function, or the wrapped component's through up to two layers of `memo`
// and `lazy`, as React's JSX types read it) lets JSX callers leave its props
@@ -428,11 +474,30 @@ function readCodeProps(
/** @param {any} tag */ tag => SKIP_TAGS.has(tag.tagName.text),
),
),
+ // A property's `type` is the prop's type; a method's is its return
+ // type, so a method prop reads as the compiler renders it.
+ declared: ownDeclarations
+ .filter(
+ /** @param {any} d */ d =>
+ d.type && !ts.isMethodSignature(d) && !ts.isMethodDeclaration(d),
+ )
+ .map(/** @param {any} d */ d => d.type.getText(d.getSourceFile())),
types: () =>
symbols.map(
/** @param {any} s */ s =>
checker.getTypeOfSymbolAtLocation(s, sourceFile),
),
+ renderings: memo(() => {
+ /** @type {string[]} */
+ const printed = [];
+ for (const s of symbols) {
+ const propType = checker.getTypeOfSymbolAtLocation(s, sourceFile);
+ for (const part of inDeclaredOrder(ts, checker, propType, s)) {
+ printed.push(checker.typeToString(part, sourceFile, flags));
+ }
+ }
+ return printed;
+ }),
});
}
@@ -449,6 +514,83 @@ function readCodeProps(
return {ok: true, props, accepts};
}
+/**
+ * A prop type's union members in the order the source declares them,
+ * through the type aliases it names; members it doesn't reach, such as the
+ * `undefined` an optional prop adds, follow, sorted by their text. The
+ * compiler's own order follows when each type was first made, so it would
+ * move with whatever read the types first.
+ * @param {any} ts
+ * @param {any} checker
+ * @param {any} type
+ * @param {any} symbol the prop
+ * @returns {any[]}
+ */
+function inDeclaredOrder(ts, checker, type, symbol) {
+ if (!type.isUnion()) return [type];
+ /** @type {any[]} */
+ const order = [];
+ const seen = new Set();
+ /** @type {(node: any) => void} */
+ const visit = node => {
+ if (ts.isParenthesizedTypeNode(node)) return visit(node.type);
+ if (ts.isUnionTypeNode(node)) return node.types.forEach(visit);
+ if (ts.isTypeReferenceNode(node) && !node.typeArguments) {
+ let target = checker.getSymbolAtLocation(node.typeName);
+ if (target && target.flags & ts.SymbolFlags.Alias) {
+ target = checker.getAliasedSymbol(target);
+ }
+ const alias = target?.declarations?.find(ts.isTypeAliasDeclaration);
+ if (alias && !alias.typeParameters) {
+ if (!seen.has(alias)) {
+ seen.add(alias);
+ visit(alias.type);
+ }
+ return;
+ }
+ }
+ const found = checker.getTypeFromTypeNode(node);
+ order.push(...(found.isUnion() ? found.types : [found]));
+ };
+ for (const declaration of symbol.declarations ?? []) {
+ if (declaration.type) visit(declaration.type);
+ }
+ /** @type {(t: any) => number} */
+ const place = t => {
+ const at = order.indexOf(t);
+ return at === -1 ? order.length : at;
+ };
+ /** @type {(t: any) => string} */
+ const text = t => checker.typeToString(t);
+ return [...type.types].sort(
+ (a, b) => place(a) - place(b) || text(a).localeCompare(text(b)),
+ );
+}
+
+/**
+ * The prop's type for a message: as the source writes it when its
+ * declarations agree, else (a method or accessor, or declarations that differ
+ * or narrow each other in an intersection) as the compiler prints it, without
+ * the `undefined` an optional prop adds.
+ * @param {CodeProp} code
+ */
+function codeTypeText(code) {
+ const written = [...new Set(code.declared)];
+ const text =
+ written.length === 1
+ ? written[0]
+ : [
+ ...new Set(
+ code
+ .renderings()
+ .filter(
+ part => !(code.required !== true && part === 'undefined'),
+ ),
+ ),
+ ].join(' | ');
+ return text.replace(/\s+/g, ' ').trim();
+}
+
/**
* The props one doc entry names. `a / b` documents each of `a` and `b`, with
* the entry's `required` (and the type split the same way when it splits
@@ -1352,6 +1494,7 @@ export function comparePropTables(tables, options) {
...base,
kind: 'not_in_code',
message: `"${propName}" is documented, but ${table.name}'s props have no "${propName}".`,
+ ...(typeof entry.type === 'string' ? {docType: entry.type} : {}),
});
continue;
}
@@ -1363,6 +1506,8 @@ export function comparePropTables(tables, options) {
message: code.required
? `"${propName}" is required in the code, but the doc does not mark it required.`
: `"${propName}" is documented as required, but it is optional in the code.`,
+ docRequired,
+ codeRequired: code.required,
});
}
}
@@ -1389,6 +1534,8 @@ export function comparePropTables(tables, options) {
message: `${table.name} declares "${code.name}", but the doc does not list it.`,
doc: table.doc,
source,
+ codeType: codeTypeText(code),
+ codeRequired: code.required,
});
}
if (untraced.length > 0) {
@@ -1419,3 +1566,200 @@ export function comparePropTables(tables, options) {
...(propsNotChecked.length > 0 ? {propsNotChecked} : {}),
};
}
+
+/**
+ * The prop tables one doc file documents, each with the export it describes.
+ * A multi-component doc names each entry's export; an entry without `props`
+ * (a reference to a sibling doc) and a hook entry are not prop tables.
+ * @param {any} doc
+ * @param {PropDriftComponent} component
+ * @returns {Array<{name: string, props: any[]}>}
+ */
+function propTables(doc, component) {
+ if (!doc || typeof doc !== 'object') return [];
+ /** @type {Array<{name: string, props: any[]}>} */
+ const tables = [];
+ // A doc's own props document the export its `name` names, which can be
+ // another file's export than the one its file is named after.
+ const own = ownName(doc, component);
+ if (Array.isArray(doc.props) && !HOOK_NAME.test(own)) {
+ tables.push({name: own, props: doc.props});
+ }
+ if (Array.isArray(doc.components)) {
+ for (const entry of doc.components) {
+ if (
+ entry &&
+ typeof entry.name === 'string' &&
+ Array.isArray(entry.props) &&
+ !(Array.isArray(doc.props) && entry.name === own) &&
+ !HOOK_NAME.test(entry.name)
+ ) {
+ tables.push({name: entry.name, props: entry.props});
+ }
+ }
+ }
+ return tables;
+}
+
+/**
+ * The export a doc's own props document: its `name`, else its record's.
+ * @param {any} doc
+ * @param {PropDriftComponent} component
+ */
+function ownName(doc, component) {
+ return typeof doc.name === 'string' && doc.name !== ''
+ ? doc.name
+ : component.name;
+}
+
+/**
+ * The stem of a `<stem>.doc.{ts,mjs,js}` file: the name of the record that
+ * owns the doc.
+ * @param {string} docPath
+ */
+function docStem(docPath) {
+ return path.basename(docPath).replace(/\.doc\.(ts|mjs|js)$/, '');
+}
+
+/**
+ * Where an entry's export lives: `<entry>.tsx` beside the doc, else the doc's
+ * own same-stem source, else the directory's `index.ts`/`index.tsx`, else the
+ * `.tsx` in the doc's folder that declares it, as discovery finds a member's.
+ * @param {string} name
+ * @param {PropDriftComponent} component
+ * @returns {string[]} candidates, in order
+ */
+function sourcesForEntry(name, component) {
+ const own = component.sourcePath ? [component.sourcePath] : [];
+ if (name === component.name) return own;
+ const dir = path.dirname(component.docPath);
+ return [
+ path.join(dir, `${name}.tsx`),
+ ...own,
+ path.join(dir, 'index.ts'),
+ path.join(dir, 'index.tsx'),
+ folderSourceFor(dir, name),
+ ].filter(
+ /** @type {(file: string | null, i: number, all: Array<string | null>) => file is string} */ (
+ (file, i, all) =>
+ file != null && all.indexOf(file) === i && fs.existsSync(file)
+ ),
+ );
+}
+
+/**
+ * Compare documented props with each component's TypeScript props: find each
+ * doc's prop tables, then compare them (`comparePropTables`).
+ * @param {PropDriftComponent[]} components
+ * @param {{packageDir: string, resolveFrom: Array<string | null | undefined>, loadDoc?: (docPath: string) => Promise<any>}} options
+ * @returns {Promise<PropDriftReport>}
+ */
+export async function comparePropDocs(components, options) {
+ const {packageDir, resolveFrom, loadDoc = loadComponentDoc} = options;
+ const rel = (/** @type {string} */ file) =>
+ path.relative(packageDir, file).split(path.sep).join('/');
+
+ /** @type {PropDriftTable[]} */
+ const tables = [];
+ /** @type {PropDriftUnchecked[]} */
+ const unchecked = [];
+ const seen = new Set();
+ // A family doc can stand behind several records: its own, named after the
+ // doc, and one per member entry that discovery records as a component of
+ // its own. A member record compares only its own entry, against its own
+ // source; the family record leaves those entries to the members.
+ /** @type {Map<string, Set<string>>} */
+ const namesByDoc = new Map();
+ for (const component of components) {
+ const names = namesByDoc.get(component.docPath) ?? new Set();
+ names.add(component.name);
+ namesByDoc.set(component.docPath, names);
+ }
+ /** @type {Map<string, Promise<any>>} */
+ const docs = new Map();
+ /** @type {Set<string>} docs whose own record is here */
+ const owned = new Set();
+ // Its own props, and every entry no member record compares: a hidden one,
+ // or one discovery doesn't record. One whose source isn't found is listed
+ // as not compared.
+ const compareOwn = (
+ /** @type {PropDriftComponent} */ component,
+ /** @type {any} */ doc,
+ ) => {
+ const members = namesByDoc.get(component.docPath) ?? new Set();
+ for (const table of propTables(doc, component)) {
+ if (table.name !== component.name && members.has(table.name)) continue;
+ const sources = sourcesForEntry(table.name, component);
+ // One table per doc: two docs that each document a component both
+ // get compared.
+ const key = `${component.docPath}\0${sources[0]}\0${table.name}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ tables.push({doc: rel(component.docPath), ...table, sources});
+ }
+ };
+ for (const component of components) {
+ let doc;
+ try {
+ let loading = docs.get(component.docPath);
+ if (!loading) {
+ loading = Promise.resolve(loadDoc(component.docPath));
+ docs.set(component.docPath, loading);
+ }
+ doc = await loading;
+ } catch (err) {
+ unchecked.push({
+ component: component.name,
+ doc: rel(component.docPath),
+ reason: `its doc does not load: ${err instanceof Error ? err.message : String(err)}`,
+ });
+ continue;
+ }
+ // The doc's own record is named after its file, or after the export its
+ // `name` names; any other record is a family member's.
+ const ownRecord =
+ component.name === docStem(component.docPath) ||
+ (doc != null &&
+ typeof doc === 'object' &&
+ ownName(doc, component) === component.name);
+ if (!ownRecord) {
+ // A family member compares its own entry.
+ const entry = Array.isArray(doc?.components)
+ ? doc.components.find(
+ (/** @type {any} */ candidate) =>
+ candidate?.name === component.name &&
+ Array.isArray(candidate.props),
+ )
+ : undefined;
+ if (!entry || HOOK_NAME.test(component.name)) continue;
+ const key = `${component.docPath}\0${component.sourcePath}\0${component.name}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ tables.push({
+ doc: rel(component.docPath),
+ name: component.name,
+ props: entry.props,
+ sources: component.sourcePath ? [component.sourcePath] : [],
+ });
+ continue;
+ }
+ owned.add(component.docPath);
+ compareOwn(component, doc);
+ }
+ // A family doc whose own record is missing, because its same-stem source
+ // is, still has its own props and unrecorded entries compared or listed.
+ for (const [docPath, loading] of docs) {
+ if (owned.has(docPath)) continue;
+ const doc = await loading.catch(() => null);
+ if (doc == null || typeof doc !== 'object') continue;
+ compareOwn({name: docStem(docPath), docPath, sourcePath: null}, doc);
+ }
+ const report = comparePropTables(tables, {packageDir, resolveFrom});
+ if (report.status === 'skipped') return report;
+ return {
+ ...report,
+ unchecked: [...unchecked, ...report.unchecked].sort((a, b) =>
+ a.component.localeCompare(b.component),
+ ),
+ };
+}
diff --git a/packages/cli/foundation/discovery/prop-drift.test.mjs b/packages/cli/foundation/discovery/prop-drift.test.mjs
index 3784d6eecf..1091c1e63c 100644
--- a/packages/cli/foundation/discovery/prop-drift.test.mjs
+++ b/packages/cli/foundation/discovery/prop-drift.test.mjs
@@ -2,7 +2,8 @@
/**
* @file Documented props against a component's TypeScript props: each kind
- * of finding, and each component it cannot read.
+ * of finding, each component it cannot read, and the visible skip when the
+ * project has no TypeScript.
*/
import * as fs from 'node:fs';
@@ -10,7 +11,12 @@ import * as os from 'node:os';
import * as path from 'node:path';
import {createRequire} from 'node:module';
import {afterEach, beforeEach, describe, expect, it} from 'vitest';
-import {comparePropTables} from './prop-drift.mjs';
+import {
+ comparePropDocs,
+ comparePropTables,
+ TYPESCRIPT_MISSING_REASON,
+} from './prop-drift.mjs';
+import {unusableTypeScriptReason} from './project-typescript.mjs';
const require = createRequire(import.meta.url);
const TYPESCRIPT_DIR = path.dirname(require.resolve('typescript/package.json'));
@@ -147,6 +153,8 @@ export function Badge(props: BadgeProps) { return null; }`,
expect(
report.findings.find(f => f.kind === 'required_mismatch'),
).toMatchObject({
+ docRequired: false,
+ codeRequired: true,
doc: 'components/Badge.doc.mjs',
source: 'components/Badge.tsx',
});
@@ -257,6 +265,125 @@ export function Select(props: Single | Multi) { return null; }`,
);
});
+ it('shows a method prop the doc leaves out with its function type, optional or not', async () => {
+ withTypeScript();
+ const picker = component(
+ 'Picker',
+ `export interface PickerProps {
+ label?: string;
+ onPick(value: string, index: number): void;
+ onClear?(reason: string): void;
+ get size(): number;
+}
+export function Picker(props: PickerProps) { return null; }`,
+ {props: [prop('label', 'string')]},
+ );
+
+ const report = await compare([picker]);
+
+ expect(
+ report.findings.map(f => `${f.prop} ${f.kind}: ${f.codeType}`),
+ ).toEqual([
+ 'onClear not_in_doc: (reason: string) => void',
+ 'onPick not_in_doc: (value: string, index: number) => void',
+ 'size not_in_doc: number',
+ ]);
+ });
+
+ it("prints a union's members in the order the source declares them", async () => {
+ withTypeScript();
+ // The same literals, made first in another order, would set the
+ // compiler's own order.
+ const ordered = component(
+ 'Ordered',
+ [
+ "type Other = 'md' | 'sm' | 'lg';",
+ 'export type Unrelated = Other;',
+ "type Small = 'lg' | 'sm';",
+ "export function Ordered(props: {size?: Small} | {size?: 'md'; label?: string}) { return null; }",
+ ].join('\n'),
+ {props: [prop('label', 'string')]},
+ );
+
+ const report = await compare([ordered]);
+
+ expect(
+ report.findings.find(finding => finding.prop === 'size')?.codeType,
+ ).toBe("'lg' | 'sm' | 'md'");
+ });
+
+ it("reads a prop that the package's defaultProps fills as optional", async () => {
+ withTypeScript();
+ // A library type that declares an optional `defaultProps`, as React's
+ // component types do, fills nothing; without strict null checks it reads
+ // as filling every prop.
+ const lib = path.join(pkg, 'node_modules', '@acme', 'lib');
+ fs.mkdirSync(lib, {recursive: true});
+ fs.writeFileSync(
+ path.join(lib, 'package.json'),
+ JSON.stringify({name: '@acme/lib', types: 'index.d.ts'}),
+ );
+ fs.writeFileSync(
+ path.join(lib, 'index.d.ts'),
+ `export interface Kind<P> { new (props: P): {}; defaultProps?: Partial<P> }
+export declare function memo<T extends (p: any) => any>(c: T): {(p: Parameters<T>[0]): null; $$typeof: symbol; type: T};
+export declare function lazy<T extends (p: any) => any>(f: () => Promise<{default: T}>): {(p: Parameters<T>[0]): null; $$typeof: symbol; _result: T};\n`,
+ );
+ fs.writeFileSync(
+ path.join(pkg, 'tsconfig.json'),
+ JSON.stringify({compilerOptions: {strict: false, jsx: 'react-jsx'}}),
+ );
+ const source = `import {type Kind, lazy, memo} from '@acme/lib';
+declare class Component<P> { constructor(props: P); props: P }
+export class Klass extends Component<{label: string; size: number}> {
+ static defaultProps = {size: 1};
+}
+export function Fn(props: {label: string; size: number}) { return null; }
+Fn.defaultProps = {size: 1};
+export function Gn(props: {label: string; size: number}) { return null; }
+Gn.defaultProps = {size: 1};
+export declare const Typed: Kind<{label: string; size: number}>;
+export const Memoed = memo(Fn);
+export const Lazied = lazy(() => Promise.resolve({default: Fn}));
+export const Thrice = memo(memo(memo(Fn)));
+export class Loose extends Component<{label: string; size: number}> { static defaultProps: any = {}; }`;
+ const props = [
+ prop('label', 'string'),
+ prop('size', 'number', {required: true}),
+ ];
+
+ const report = await compare([
+ ...'Klass Fn Typed Memoed Lazied Thrice Loose'
+ .split(' ')
+ .map(name => component(name, source, {props})),
+ component('Gn', source, {
+ props: [prop('label', 'string'), prop('size', 'number')],
+ }),
+ ]);
+
+ // JSX callers may leave out a prop defaultProps fills (for `memo` and
+ // `lazy`, the wrapped component's, two layers deep as React's types read
+ // it; `any` fills every prop), so a doc that marks it required disagrees
+ // with the code, and one that doesn't agrees.
+ expect(kinds(report)).toEqual([
+ 'Fn.label required_mismatch',
+ 'Fn.size required_mismatch',
+ 'Gn.label required_mismatch',
+ 'Klass.label required_mismatch',
+ 'Klass.size required_mismatch',
+ 'Lazied.label required_mismatch',
+ 'Lazied.size required_mismatch',
+ 'Loose.size required_mismatch',
+ 'Memoed.label required_mismatch',
+ 'Memoed.size required_mismatch',
+ 'Thrice.label required_mismatch',
+ 'Typed.label required_mismatch',
+ ]);
+ expect(
+ report.findings.find(f => f.component === 'Fn' && f.prop === 'size'),
+ ).toMatchObject({docRequired: true, codeRequired: false});
+ });
+
it('lists each component whose props it cannot read as not compared', async () => {
withTypeScript();
const tsconfig = path.join(pkg, 'tsconfig.json');
@@ -552,3 +679,519 @@ export const Wrapped = forwardRef<HTMLButtonElement, {label?: string}>((props, r
}
});
});
+
+/**
+ * A multi-component doc's entry.
+ * @param {string} name
+ * @param {any[]} props
+ */
+const entry = (name, props) => ({
+ name,
+ displayName: name,
+ description: 'Fixture.',
+ props,
+});
+
+/** @param {import('./prop-drift.mjs').PropDriftComponent[]} components */
+function compareDocs(components) {
+ return comparePropDocs(components, {packageDir: pkg, resolveFrom: [pkg]});
+}
+
+describe('comparePropDocs', () => {
+ it('compares each entry of a multi-component doc against its own export, and skips hooks', async () => {
+ withTypeScript();
+ const tabs = component(
+ 'Tabs',
+ `export function Tabs(props: {value: string}) { return null; }
+export function Tab(props: {value: string; isDisabled?: boolean}) { return null; }
+export function useTabs(options: {value: string}) { return options; }`,
+ {
+ components: [
+ entry('Tabs', [prop('value', 'string', {required: true})]),
+ entry('Tab', [
+ prop('value', 'string', {required: true}),
+ prop('isSelected', 'boolean'),
+ ]),
+ {
+ name: 'useTabs',
+ displayName: 'useTabs',
+ description: 'Fixture.',
+ params: [
+ {
+ name: 'options',
+ type: '{value: string}',
+ description: 'Fixture.',
+ },
+ ],
+ },
+ ],
+ },
+ );
+
+ const report = await compareDocs([tabs]);
+
+ expect(report.components).toBe(2);
+ expect(kinds(report)).toEqual([
+ 'Tab.isDisabled not_in_doc',
+ 'Tab.isSelected not_in_code',
+ ]);
+ });
+
+ it('compares a member record only against its own source, and the family record leaves that member alone', async () => {
+ withTypeScript();
+ const status = component(
+ 'Status',
+ 'export function Status(props: {value: string}) { return null; }\n',
+ {
+ components: [
+ entry('Status', [prop('value', 'string', {required: true})]),
+ entry('StatusGlyph', [
+ prop('size', 'number'),
+ prop('tone', 'string'),
+ ]),
+ ],
+ },
+ );
+ const glyphSource = path.join(pkg, 'components', 'StatusView.tsx');
+ fs.writeFileSync(
+ glyphSource,
+ 'export function StatusGlyph(props: {size?: number}) { return null; }\n',
+ );
+
+ const report = await compareDocs([
+ status,
+ {...status, name: 'StatusGlyph', sourcePath: glyphSource},
+ ]);
+
+ expect(report.unchecked).toEqual([]);
+ expect(report.components).toBe(2);
+ expect(kinds(report)).toEqual(['StatusGlyph.tone not_in_code']);
+ expect(report.findings[0].source).toBe('components/StatusView.tsx');
+ });
+
+ it('lists a member record that no file in the package declares as not compared', async () => {
+ withTypeScript();
+ const status = component(
+ 'Status',
+ 'export function Status(props: {value: string}) { return null; }\n',
+ {
+ components: [
+ entry('Status', [prop('value', 'string', {required: true})]),
+ entry('StatusGlyph', [prop('size', 'number')]),
+ ],
+ },
+ );
+
+ // Only another folder, or built output, declares the member.
+ const report = await compareDocs([
+ status,
+ {...status, name: 'StatusGlyph', sourcePath: null},
+ ]);
+
+ expect(report.components).toBe(1);
+ expect(report.findings).toEqual([]);
+ expect(report.unchecked).toEqual([
+ {
+ component: 'StatusGlyph',
+ doc: 'components/Status.doc.mjs',
+ reason: 'no source file for StatusGlyph',
+ },
+ ]);
+ });
+
+ it('compares every entry of a family doc named after another export, and lists one with no source as not compared', async () => {
+ withTypeScript();
+ const menu = component(
+ 'Menu',
+ [
+ 'export function MenuRoot(props: {open?: boolean}) { return null; }',
+ 'export function MenuItem(props: {value: string}) { return null; }',
+ ].join('\n'),
+ {
+ name: 'MenuRoot',
+ hiddenComponents: ['MenuItem', 'MenuPart'],
+ components: [
+ entry('MenuItem', [prop('label', 'string')]),
+ entry('MenuGhost', [prop('tone', 'string')]),
+ entry('MenuPart', [prop('tone', 'string')]),
+ ],
+ },
+ );
+ // A hidden entry declared in another file of the doc's folder.
+ fs.writeFileSync(
+ path.join(pkg, 'components', 'menu-parts.tsx'),
+ 'export function MenuPart(props: {depth?: number}) { return null; }\n',
+ );
+
+ // Discovery records the doc under `MenuRoot` and leaves the hidden
+ // `MenuItem` and `MenuPart` and the unbuilt `MenuGhost` without records
+ // of their own.
+ const report = await compareDocs([{...menu, name: 'MenuRoot'}]);
+
+ expect(kinds(report)).toEqual([
+ 'MenuItem.label not_in_code',
+ 'MenuItem.value not_in_doc',
+ 'MenuPart.depth not_in_doc',
+ 'MenuPart.tone not_in_code',
+ ]);
+ expect(report.unchecked).toEqual([
+ {
+ component: 'MenuGhost',
+ doc: 'components/Menu.doc.mjs',
+ reason: 'Menu.tsx has no export named MenuGhost',
+ },
+ ]);
+ });
+
+ it("compares a doc's own props with the export its name names, which another file can hold", async () => {
+ withTypeScript();
+ const status = component(
+ 'Status',
+ 'export function Status(props: {value: string}) { return null; }\n',
+ {name: 'StatusView', props: [prop('size', 'number')]},
+ );
+ const viewSource = path.join(pkg, 'components', 'StatusView.tsx');
+ fs.writeFileSync(
+ viewSource,
+ 'export function StatusView(props: {size?: number}) { return null; }\n',
+ );
+
+ // Discovery names the record after the file, or after the export.
+ const byFile = await compareDocs([status]);
+ const byExport = await compareDocs([
+ {...status, name: 'StatusView', sourcePath: viewSource},
+ ]);
+
+ for (const report of [byFile, byExport]) {
+ expect(report.unchecked).toEqual([]);
+ expect(report.components).toBe(1);
+ expect(report.findings).toEqual([]);
+ }
+ });
+
+ it('compares a table for one component in each doc that has one', async () => {
+ withTypeScript();
+ const title = prop('title', 'string', {required: true});
+ const list = component(
+ 'List',
+ 'export function List(props: {label: string}) { return null; }\n',
+ {
+ components: [
+ entry('List', [prop('label', 'string', {required: true})]),
+ entry('ListGroup', [title]),
+ ],
+ },
+ );
+ const group = component(
+ 'ListGroup',
+ 'export function ListGroup(props: {title: string}) { return null; }\n',
+ {props: [title, prop('stale', 'string')]},
+ );
+
+ const report = await compareDocs([list, group]);
+
+ expect(report.components).toBe(3);
+ expect(kinds(report)).toEqual(['ListGroup.stale not_in_code']);
+ expect(report.findings[0].doc).toBe('components/ListGroup.doc.mjs');
+ });
+
+ it('lists every component as not compared when a declaration file the config includes, or a type package it names, does not resolve', async () => {
+ withTypeScript();
+ const tsconfig = path.join(pkg, 'tsconfig.json');
+ const config = JSON.parse(fs.readFileSync(tsconfig, 'utf8'));
+ /** @param {object} options */
+ const configure = options =>
+ fs.writeFileSync(
+ tsconfig,
+ JSON.stringify({
+ ...config,
+ compilerOptions: {...config.compilerOptions, ...options},
+ include: ['components', 'types'],
+ }),
+ );
+ fs.mkdirSync(path.join(pkg, 'types'));
+ const globals = path.join(pkg, 'types', 'globals.d.ts');
+ const tables = () => [
+ component(
+ 'Omitted',
+ 'export function Omitted(props: Omit<{label: string; size?: number}, keyof MissingProps>) { return null; }\n',
+ {
+ props: [
+ prop('label', 'string', {required: true}),
+ prop('size', 'number'),
+ ],
+ },
+ ),
+ component(
+ 'Plain',
+ 'export function Plain(props: {label?: string}) { return null; }\n',
+ {props: [prop('label', 'string')]},
+ ),
+ ];
+ /** @param {RegExp} reason */
+ const unread = reason =>
+ ['Omitted', 'Plain'].map(name => ({
+ component: name,
+ doc: `components/${name}.doc.mjs`,
+ reason: expect.stringMatching(reason),
+ }));
+
+ // A global type made from a package that isn't installed.
+ configure({});
+ fs.writeFileSync(
+ globals,
+ "import type {Props} from '@acme/not-installed';\ndeclare global { type MissingProps = Props; }\n",
+ );
+ let report = await compare(tables());
+ expect(report.findings).toEqual([]);
+ expect(report.unchecked).toEqual(
+ unread(
+ /depends on `@acme\/not-installed` \(imported in \.\.\/types\/globals\.d\.ts\)/,
+ ),
+ );
+
+ // A global type made from a name declared nowhere.
+ fs.writeFileSync(
+ globals,
+ 'declare global { type MissingProps = NowhereProps; }\nexport {};\n',
+ );
+ report = await compare(tables());
+ expect(report.findings).toEqual([]);
+ expect(report.unchecked).toEqual(
+ unread(
+ /depends on `NowhereProps` \(used in \.\.\/types\/globals\.d\.ts\)/,
+ ),
+ );
+
+ // A type package the config names that isn't installed.
+ fs.writeFileSync(
+ globals,
+ 'declare global { type MissingProps = {id?: string}; }\nexport {};\n',
+ );
+ configure({types: ['@acme/not-installed-globals']});
+ report = await compare(tables());
+ expect(report.findings).toEqual([]);
+ expect(report.unchecked).toEqual(
+ unread(
+ /depends on the types `@acme\/not-installed-globals` \(named in \.\.\/tsconfig\.json\)/,
+ ),
+ );
+
+ // Both resolved: compared.
+ configure({types: []});
+ report = await compare(tables());
+ expect(report.unchecked).toEqual([]);
+ expect(report.components).toBe(2);
+ });
+
+ it("lists every table, with the error, when the package's TypeScript config has an error", async () => {
+ withTypeScript();
+ fs.writeFileSync(
+ path.join(pkg, 'tsconfig.json'),
+ JSON.stringify({extends: './missing-base.json'}),
+ );
+ const titled = component(
+ 'Titled',
+ 'export function Titled(props: {title?: string}) { return null; }\n',
+ {props: [prop('title', 'string')]},
+ );
+
+ const report = await compare([titled]);
+
+ expect(report.components).toBe(0);
+ expect(report.unchecked).toEqual([
+ expect.objectContaining({
+ component: 'Titled',
+ reason: expect.stringMatching(
+ /config has an error.*missing-base\.json/,
+ ),
+ }),
+ ]);
+ });
+
+ it('accepts a name through an index signature only as TypeScript would', async () => {
+ withTypeScript();
+ const keyed = component(
+ 'Keyed',
+ [
+ 'export interface KeyedProps {',
+ ' [key: `data-${string}`]: string | undefined;',
+ ' [key: `${string}:${string}`]: string;',
+ ' [key: `col${number}`]: number;',
+ ' [key: `on${Capitalize<string>}`]: () => void;',
+ '}',
+ 'export function Keyed(props: KeyedProps) { return null; }',
+ ].join('\n'),
+ {
+ props: [
+ prop('data-section', 'string'),
+ prop('a:b', 'string'),
+ prop('col2', 'number'),
+ prop('onClick', '() => void'),
+ prop('elevation', 'string'),
+ prop('colSpan', 'string'),
+ prop('onclick', 'string'),
+ ],
+ },
+ );
+ const empty = component(
+ 'Empty',
+ `interface EmptyProps { label?: string }
+export function Empty(props: EmptyProps | Record<string, never>) { return null; }`,
+ {props: [prop('label', 'string'), prop('elevation', 'number')]},
+ );
+ const typedAny = component(
+ 'TypedAny',
+ 'export function TypedAny(props: any) { return null; }\n',
+ {props: [prop('label', 'string')]},
+ );
+ const anyConst = component(
+ 'AnyConst',
+ 'export const AnyConst: any = null;\n',
+ {props: [prop('label', 'string')]},
+ );
+
+ const report = await compare([keyed, empty, typedAny, anyConst]);
+
+ expect(kinds(report)).toEqual([
+ 'Empty.elevation not_in_code',
+ 'Keyed.colSpan not_in_code',
+ 'Keyed.elevation not_in_code',
+ 'Keyed.onclick not_in_code',
+ ]);
+ expect(report.unchecked.map(u => [u.component, u.reason])).toEqual([
+ ['AnyConst', expect.stringContaining('typed `any`')],
+ ['TypedAny', expect.stringContaining('typed `any`')],
+ ]);
+ });
+
+ it("reads props through React's component types, lists the ones typed any or named by the element they render, and loads the ambient types tsconfig includes", async () => {
+ withTypeScript();
+ fs.mkdirSync(path.join(pkg, 'node_modules', '@types'), {recursive: true});
+ fs.symlinkSync(
+ path.dirname(require.resolve('@types/react/package.json')),
+ path.join(pkg, 'node_modules', '@types', 'react'),
+ 'dir',
+ );
+ const tsconfig = path.join(pkg, 'tsconfig.json');
+ const config = JSON.parse(fs.readFileSync(tsconfig, 'utf8'));
+ fs.writeFileSync(
+ tsconfig,
+ JSON.stringify({...config, include: ['components', 'types']}),
+ );
+ fs.mkdirSync(path.join(pkg, 'types'));
+ fs.writeFileSync(
+ path.join(pkg, 'types', 'ambient.d.ts'),
+ 'interface AmbientProps { label?: string }\n',
+ );
+ const source = `import {forwardRef, memo, type FC, type ComponentType, type ComponentPropsWithoutRef, type ElementType} from 'react';
+export function Poly<E extends ElementType = 'div'>(props: {as?: E; padding?: number} & Omit<ComponentPropsWithoutRef<E>, 'as' | 'padding'>) { return null; }
+export const Fc: FC<any> = () => null;
+export const Memo = memo((props: any) => null);
+export const Fwd = forwardRef<HTMLDivElement, any>((props, ref) => null);
+export const FwdOmit = forwardRef<HTMLDivElement, Omit<any, 'as'>>((props, ref) => null);
+export const FwdPartial = memo(forwardRef<HTMLDivElement, Partial<any>>((props, ref) => null));
+export function Ambient(props: AmbientProps) { return null; }
+export const Typed: ComponentType<{label?: string}> = () => null;
+const withName = <P,>(c: ComponentType<P>): ComponentType<P> => c;
+export const Hoc = withName((props: {label?: string}) => null);`;
+ const props = [prop('label', 'string'), prop('elevation', 'number')];
+
+ const report = await compare(
+ 'Fc Memo Fwd FwdOmit FwdPartial Poly Ambient Typed Hoc'
+ .split(' ')
+ .map(name => component(name, source, {props})),
+ );
+
+ expect(kinds(report)).toEqual(
+ 'Ambient Hoc Typed'
+ .split(' ')
+ .map(name => `${name}.elevation not_in_code`),
+ );
+ expect(report.unchecked.map(u => [u.component, u.reason])).toEqual(
+ ['Fc', 'Fwd', 'FwdOmit', 'FwdPartial', 'Memo', 'Poly'].map(name => [
+ name,
+ expect.stringContaining(
+ name === 'Poly' ? 'from a type parameter' : 'typed `any`',
+ ),
+ ]),
+ );
+ });
+
+ it('reads names that list several props, spreads, and fields through arrays, tuples, unions and index signatures', async () => {
+ withTypeScript();
+ const menu = component(
+ 'Menu',
+ [
+ 'export interface MenuProps {',
+ ' onOpen?: () => void;',
+ ' onClose?: () => void;',
+ ' value?: {label: string; items: ReadonlyArray<{id: string}>};',
+ ' labels?: Record<string, string>;',
+ ' slots?: {[key: `slot-${string}`]: string};',
+ " rows?: Array<{kind: 'a'; total: string} | {kind: 'b'}>;",
+ ' grid?: Array<Array<{id: string}>>;',
+ ' pair?: readonly [{id: string}, {id: number}];',
+ '}',
+ 'export function Menu(props: MenuProps) { return null; }',
+ ].join('\n'),
+ {
+ props: [
+ prop('onOpen / onClose', '() => void / () => void'),
+ prop('...rest', 'Omit<OtherProps, "x">'),
+ ...['value.label', 'value.items[].id', 'value.missing'].map(name =>
+ prop(name, 'string'),
+ ),
+ ...['labels.close', 'slots.slot-a', 'slots.other'].map(name =>
+ prop(name, 'string'),
+ ),
+ ...['rows[].total', 'grid[][].id', 'grid[][].size', 'pair[].id'].map(
+ name => prop(name, 'string'),
+ ),
+ ],
+ },
+ );
+
+ expect(kinds(await compare([menu]))).toEqual([
+ 'Menu.grid[][].size not_in_code',
+ 'Menu.slots.other not_in_code',
+ 'Menu.value.missing not_in_code',
+ ]);
+ });
+
+ it('skips with a reason, and compares nothing, without a TypeScript it can use', async () => {
+ const badge = component(
+ 'Badge',
+ 'export function Badge(props: {label: string}) { return null; }\n',
+ {props: [prop('label', 'number')]},
+ );
+ const skipped = (/** @type {string} */ reason) => ({
+ status: 'skipped',
+ reason,
+ components: 0,
+ findings: [],
+ unchecked: [],
+ });
+
+ expect(await compare([badge])).toEqual(skipped(TYPESCRIPT_MISSING_REASON));
+ // TypeScript 7 has no JavaScript compiler API to load.
+ const dir = path.join(pkg, 'node_modules', 'typescript');
+ fs.mkdirSync(dir, {recursive: true});
+ fs.writeFileSync(
+ path.join(dir, 'package.json'),
+ JSON.stringify({
+ name: 'typescript',
+ version: '7.0.0',
+ exports: {'./package.json': './package.json'},
+ }),
+ );
+ expect(await compare([badge])).toEqual(
+ skipped(
+ unusableTypeScriptReason(
+ '7.0.0',
+ 'documented props were not compared with the code',
+ ),
+ ),
+ );
+ });
+});
diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjs
index e023576a78..6b0b5816bb 100644
--- a/packages/cli/foundation/response/response-types.doc.mjs
+++ b/packages/cli/foundation/response/response-types.doc.mjs
@@ -342,7 +342,7 @@ export const doc = {
{
value: 'integration.component-conflicts',
description:
- 'validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking conflicts where an integration component name is also owned by Core; each conflict includes the exact package-qualified command.',
+ 'validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking conflicts where an integration component name is also owned by Core; each conflict includes the exact package-qualified command. When the manifest loads and declares a components root, propDrift compares documented props with the TypeScript props: status (checked | skipped), reason, typescript, components, findings (all warnings), unchecked, and propsNotChecked.',
},
{
value: 'integration.doc-conflicts',
diff --git a/packages/cli/test-utils/text-projection.mjs b/packages/cli/test-utils/text-projection.mjs
new file mode 100644
index 0000000000..f9d587e298
--- /dev/null
+++ b/packages/cli/test-utils/text-projection.mjs
@@ -0,0 +1,46 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Assert that a command's text view shows every field its JSON carries
+ * (spec AST-017 FR13).
+ */
+
+import {expect} from 'vitest';
+
+/**
+ * Assert the text shows every field of each JSON item: the record whose
+ * `keys` lines match the item holds each of its non-empty fields, with the
+ * value the formatter renders (arrays comma-joined, `severity` as its status
+ * token). An empty value has no line, as the formatter skips it.
+ * @param {string} output the command's text output
+ * @param {Record<string, unknown>[]} items
+ * @param {string[]} keys fields that pick out each item's record
+ */
+export function expectRecordsCarry(output, items, keys) {
+ const blocks = output.split(/\n{2,}/).map(block =>
+ Object.fromEntries(
+ block.split('\n').flatMap(line => {
+ const match = /^([A-Za-z]+):\s+(.*)$/.exec(line);
+ return match ? [[match[1], match[2]]] : [];
+ }),
+ ),
+ );
+ /** @param {string} field @param {unknown} value */
+ const shown = (field, value) =>
+ field === 'severity'
+ ? {warning: '[warn]', error: '[fail]'}[String(value)]
+ : Array.isArray(value)
+ ? value.join(', ')
+ : String(value);
+ for (const item of items) {
+ const block = blocks.find(b =>
+ keys.every(key => b[key] === shown(key, item[key])),
+ );
+ expect(block, JSON.stringify(item)).toBeDefined();
+ for (const [field, value] of Object.entries(item)) {
+ if (value == null || value === '') continue;
+ if (Array.isArray(value) && value.length === 0) continue;
+ expect([field, block?.[field]]).toEqual([field, shown(field, value)]);
+ }
+ }
+}
diff --git a/packages/cli/test/core-prop-docs.known-drift.json b/packages/cli/test/core-prop-docs.known-drift.json
new file mode 100644
index 0000000000..7c583c3240
--- /dev/null
+++ b/packages/cli/test/core-prop-docs.known-drift.json
@@ -0,0 +1,104 @@
+[
+ "src/AppShell/AppShell.doc.mjs AppShell.children required_mismatch",
+ "src/Badge/Badge.doc.mjs Badge.label required_mismatch",
+ "src/Center/Center.doc.mjs Center.children required_mismatch",
+ "src/CommandPalette/CommandPaletteInput.doc.mjs CommandPaletteInput.onChange not_in_doc",
+ "src/ComplexSelector/ComplexSelector.doc.mjs ComplexSelector.description not_in_doc",
+ "src/ComplexSelector/ComplexSelector.doc.mjs ComplexSelector.isLabelHidden not_in_doc",
+ "src/ComplexSelector/ComplexSelector.doc.mjs ComplexSelector.isOptional not_in_doc",
+ "src/ComplexSelector/ComplexSelector.doc.mjs ComplexSelector.isRequired not_in_doc",
+ "src/ComplexSelector/ComplexSelector.doc.mjs ComplexSelector.labelTooltip not_in_doc",
+ "src/DateRangeInput/DateRangeInput.doc.mjs DateRangeInput.containerClassName not_in_doc",
+ "src/DateRangeInput/DateRangeInput.doc.mjs DateRangeInput.containerStyle not_in_doc",
+ "src/DateRangeInput/DateRangeInput.doc.mjs DateRangeInput.controlClassName not_in_doc",
+ "src/DateRangeInput/DateRangeInput.doc.mjs DateRangeInput.controlStyle not_in_doc",
+ "src/DateTimeInput/DateTimeInput.doc.mjs DateTimeInput.containerClassName not_in_doc",
+ "src/DateTimeInput/DateTimeInput.doc.mjs DateTimeInput.containerStyle not_in_doc",
+ "src/DateTimeInput/DateTimeInput.doc.mjs DateTimeInput.controlClassName not_in_doc",
+ "src/DateTimeInput/DateTimeInput.doc.mjs DateTimeInput.controlStyle not_in_doc",
+ "src/Dialog/DialogHeader.doc.mjs DialogHeader.title required_mismatch",
+ "src/DropdownMenu/DropdownMenu.doc.mjs DropdownMenu.items required_mismatch",
+ "src/DropdownMenu/DropdownMenuCheckboxItem.doc.mjs DropdownMenuCheckboxItem.label required_mismatch",
+ "src/DropdownMenu/DropdownMenuCheckboxItem.doc.mjs DropdownMenuCheckboxItem.value required_mismatch",
+ "src/DropdownMenu/DropdownMenuItem.doc.mjs DropdownMenuItem.isDisabled not_in_doc",
+ "src/DropdownMenu/DropdownMenuItem.doc.mjs DropdownMenuItem.label required_mismatch",
+ "src/DropdownMenu/DropdownMenuRadioGroup.doc.mjs DropdownMenuRadioGroup.children required_mismatch",
+ "src/DropdownMenu/DropdownMenuRadioGroup.doc.mjs DropdownMenuRadioGroup.label required_mismatch",
+ "src/DropdownMenu/DropdownMenuRadioGroup.doc.mjs DropdownMenuRadioGroup.onChange required_mismatch",
+ "src/DropdownMenu/DropdownMenuRadioGroup.doc.mjs DropdownMenuRadioGroup.value required_mismatch",
+ "src/DropdownMenu/DropdownMenuRadioItem.doc.mjs DropdownMenuRadioItem.label required_mismatch",
+ "src/DropdownMenu/DropdownMenuRadioItem.doc.mjs DropdownMenuRadioItem.value required_mismatch",
+ "src/DropdownMenu/DropdownMenuSubMenu.doc.mjs DropdownMenuSubMenu.children required_mismatch",
+ "src/DropdownMenu/DropdownMenuSubMenu.doc.mjs DropdownMenuSubMenu.label required_mismatch",
+ "src/DropdownMenu/DropdownMenuSubMenu.doc.mjs DropdownMenuSubMenu.menuDataTestId not_in_doc",
+ "src/Field/FieldLabel.doc.mjs FieldLabel.description not_in_doc",
+ "src/Field/FieldLabel.doc.mjs FieldLabel.descriptionID not_in_doc",
+ "src/Field/FieldLabel.doc.mjs FieldLabel.isGroupLabel not_in_doc",
+ "src/Field/FieldLabel.doc.mjs FieldLabel.labelID not_in_doc",
+ "src/Grid/Grid.doc.mjs Grid.rowHeight not_in_doc",
+ "src/HoverCard/HoverCard.doc.mjs HoverCard.children required_mismatch",
+ "src/IconButton/IconButton.doc.mjs IconButton.as not_in_doc",
+ "src/IconButton/IconButton.doc.mjs IconButton.form not_in_doc",
+ "src/IconButton/IconButton.doc.mjs IconButton.href not_in_doc",
+ "src/IconButton/IconButton.doc.mjs IconButton.isInterruptible not_in_doc",
+ "src/IconButton/IconButton.doc.mjs IconButton.name not_in_doc",
+ "src/IconButton/IconButton.doc.mjs IconButton.rel not_in_doc",
+ "src/IconButton/IconButton.doc.mjs IconButton.target not_in_doc",
+ "src/IconButton/IconButton.doc.mjs IconButton.type not_in_doc",
+ "src/IconButton/IconButton.doc.mjs IconButton.value not_in_doc",
+ "src/IconButton/IconButton.doc.mjs IconButton.width not_in_doc",
+ "src/Layout/Layout.doc.mjs Layout.children not_in_doc",
+ "src/Layout/LayoutFooter.doc.mjs LayoutFooter.padding not_in_doc",
+ "src/Layout/LayoutHeader.doc.mjs LayoutHeader.padding not_in_doc",
+ "src/Link/Link.doc.mjs Link.type not_in_doc",
+ "src/List/List.doc.mjs List.children required_mismatch",
+ "src/MobileNav/MobileNav.doc.mjs MobileNav.label not_in_doc",
+ "src/MoreMenu/MoreMenu.doc.mjs MoreMenu.isMenuOpen not_in_doc",
+ "src/MultiSelector/MultiSelector.doc.mjs MultiSelector.labelTooltip not_in_doc",
+ "src/PowerSearch/PowerSearch.doc.mjs PowerSearch.components not_in_doc",
+ "src/Resizable/Resizable.doc.mjs ResizeHandle.position not_in_doc",
+ "src/Resizable/Resizable.doc.mjs ResizeHandle.resizable required_mismatch",
+ "src/Selector/Selector.doc.mjs Selector.changeAction not_in_doc",
+ "src/Selector/Selector.doc.mjs Selector.isDefaultOpen not_in_doc",
+ "src/Selector/Selector.doc.mjs Selector.labelTooltip not_in_doc",
+ "src/Selector/Selector.doc.mjs Selector.placement not_in_doc",
+ "src/SideNav/SideNav.doc.mjs SideNav.children required_mismatch",
+ "src/SideNav/SideNavHeading.doc.mjs SideNavHeading.as not_in_doc",
+ "src/SideNav/SideNavSection.doc.mjs SideNavSection.children required_mismatch",
+ "src/Table/Table.doc.mjs Table.emptyState not_in_doc",
+ "src/Table/Table.doc.mjs Table.scrollWrapper not_in_doc",
+ "src/Table/TableCell.doc.mjs TableCell.colSpan not_in_doc",
+ "src/Table/TableCell.doc.mjs TableCell.contextMenuActions not_in_doc",
+ "src/Table/TableCell.doc.mjs TableCell.headers not_in_doc",
+ "src/Table/TableCell.doc.mjs TableCell.rowSpan not_in_doc",
+ "src/Table/TableCell.doc.mjs TableCell.scope not_in_doc",
+ "src/Table/TableHeaderCell.doc.mjs TableHeaderCell.contextMenuActions not_in_doc",
+ "src/Table/TableHeaderCell.doc.mjs TableHeaderCell.scope not_in_doc",
+ "src/Table/TableRow.doc.mjs TableRow.isHeaderRow not_in_doc",
+ "src/Table/TableSelectionToolbar.doc.mjs TableSelectionToolbar.centerContent not_in_doc",
+ "src/Table/TableSelectionToolbar.doc.mjs TableSelectionToolbar.dividers not_in_doc",
+ "src/Table/TableSelectionToolbar.doc.mjs TableSelectionToolbar.gap not_in_doc",
+ "src/Table/TableSelectionToolbar.doc.mjs TableSelectionToolbar.orientation not_in_doc",
+ "src/TimeInput/TimeInput.doc.mjs TimeInput.containerClassName not_in_doc",
+ "src/TimeInput/TimeInput.doc.mjs TimeInput.containerStyle not_in_doc",
+ "src/TimeInput/TimeInput.doc.mjs TimeInput.controlClassName not_in_doc",
+ "src/TimeInput/TimeInput.doc.mjs TimeInput.controlStyle not_in_doc",
+ "src/TimeInput/TimeInput.doc.mjs TimeInput.hasAutoFocus not_in_doc",
+ "src/Toast/Toast.doc.mjs Toast.autoHideDuration required_mismatch",
+ "src/Toast/Toast.doc.mjs Toast.collisionBehavior not_in_code",
+ "src/Toast/Toast.doc.mjs Toast.isAutoHide required_mismatch",
+ "src/Toast/Toast.doc.mjs Toast.isExiting not_in_doc",
+ "src/Toast/Toast.doc.mjs Toast.onHide not_in_code",
+ "src/Toast/Toast.doc.mjs Toast.type required_mismatch",
+ "src/Toast/Toast.doc.mjs Toast.uniqueID not_in_code",
+ "src/Tokenizer/Tokenizer.doc.mjs Tokenizer.onKeyDown not_in_doc",
+ "src/Tooltip/Tooltip.doc.mjs Tooltip.content required_mismatch",
+ "src/TopNav/TopNavHeading.doc.mjs TopNavHeading.logoLabel not_in_doc",
+ "src/TopNav/TopNavItem.doc.mjs TopNavItem.download not_in_doc",
+ "src/TopNav/TopNavItem.doc.mjs TopNavItem.referrerPolicy not_in_doc",
+ "src/TopNav/TopNavItem.doc.mjs TopNavItem.rel not_in_doc",
+ "src/TopNav/TopNavItem.doc.mjs TopNavItem.size not_in_doc",
+ "src/TopNav/TopNavItem.doc.mjs TopNavItem.target not_in_doc",
+ "src/Typeahead/Typeahead.doc.mjs Typeahead.onKeyDown not_in_doc",
+ "src/VisuallyHidden/VisuallyHidden.doc.mjs VisuallyHidden.children required_mismatch"
+]
diff --git a/packages/cli/test/core-prop-docs.test.mjs b/packages/cli/test/core-prop-docs.test.mjs
new file mode 100644
index 0000000000..0b7c9ff1af
--- /dev/null
+++ b/packages/cli/test/core-prop-docs.test.mjs
@@ -0,0 +1,86 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Core's own component docs against Core's TypeScript props, with the
+ * same comparison `astryx doctor integration components` runs for an
+ * integration. Drift that Core already had when the check arrived is listed
+ * in `core-prop-docs.known-drift.json`; the list only shrinks. A new
+ * difference fails here, and so does a listed one that is gone, so fixing a
+ * doc means deleting its line.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {describe, expect, it} from 'vitest';
+import {comparePropDocs} from '../foundation/discovery/prop-drift.mjs';
+
+const CLI = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const CORE = path.resolve(CLI, '..', 'core');
+const KNOWN = path.join(CLI, 'test', 'core-prop-docs.known-drift.json');
+
+/**
+ * Every `<Name>.doc.mjs` under Core's src, as the command reads a package's
+ * docs: with its same-stem `<Name>.tsx`, or with none.
+ */
+function corePairs() {
+ /** @type {Array<{name: string, docPath: string, sourcePath: string | null}>} */
+ const pairs = [];
+ /** @param {string} dir */
+ const walk = dir => {
+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
+ if (entry.name === 'node_modules' || entry.name === '__tests__') continue;
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) walk(full);
+ else if (entry.name.endsWith('.doc.mjs')) {
+ const name = entry.name.slice(0, -'.doc.mjs'.length);
+ const sourcePath = path.join(dir, `${name}.tsx`);
+ pairs.push({
+ name,
+ docPath: full,
+ sourcePath: fs.existsSync(sourcePath) ? sourcePath : null,
+ });
+ }
+ }
+ };
+ walk(path.join(CORE, 'src'));
+ return pairs.sort((a, b) => a.docPath.localeCompare(b.docPath));
+}
+
+describe("Core's component docs match Core's props", () => {
+ it('has no prop drift beyond the known list, and the list holds nothing fixed', async () => {
+ const report = await comparePropDocs(corePairs(), {
+ packageDir: CORE,
+ resolveFrom: [CORE],
+ });
+ expect(report.status).toBe('checked');
+ // A doc whose own export has no same-stem source, which discovery flags
+ // in an integration: listed, never compared as a guess.
+ expect(report.unchecked.map(u => `${u.doc} ${u.component}`)).toEqual([
+ 'src/Chat/ChatComposerTokenElement.doc.mjs ChatComposerTokenElement',
+ 'src/ContextMenu/ContextMenuItem.doc.mjs ContextMenuItem',
+ 'src/Text/Heading.doc.mjs Heading',
+ 'src/theme/SyntaxTheme.doc.mjs SyntaxTheme',
+ ]);
+
+ /** @type {string[]} */
+ const known = JSON.parse(fs.readFileSync(KNOWN, 'utf8'));
+ const found = new Map(
+ report.findings.map(f => [
+ `${f.doc} ${f.component}.${f.prop} ${f.kind}`,
+ f.message,
+ ]),
+ );
+ const added = [...found].filter(([key]) => !known.includes(key));
+ const fixed = known.filter(key => !found.has(key));
+
+ expect(
+ added.map(([key, message]) => `${key}: ${message}`),
+ 'Fix these docs (or the props) so they agree; do not add them to core-prop-docs.known-drift.json.',
+ ).toEqual([]);
+ expect(
+ fixed,
+ 'These no longer differ: delete them from core-prop-docs.known-drift.json.',
+ ).toEqual([]);
+ }, 120_000);
+});