An open source design system that's fully customizable and agent ready
TypeScript
feat(cli): compare documented component props with the TypeScript source (#7663)
Joey4787e3fdf9d8
diff --git a/.changeset/doctor-prop-comparison.md b/.changeset/doctor-prop-comparison.mdnew file mode 100644index 0000000000..c272d5bea4--- /dev/null+++ b/.changeset/doctor-prop-comparison.md@@ -0,0 +1,6 @@+---+'@astryxdesign/cli': patch+---++[chore] Internal groundwork for `astryx doctor integration components`: a comparison of the props a component doc documents with the props its TypeScript source declares, read with the project's own `typescript`. Nothing reaches it yet, so the CLI's behavior and output do not change; the command starts running it in a later change, which describes what users see.+@josephfarinadiff --git a/packages/cli/foundation/discovery/prop-drift.mjs b/packages/cli/foundation/discovery/prop-drift.mjsnew file mode 100644index 0000000000..1c7b52d305--- /dev/null+++ b/packages/cli/foundation/discovery/prop-drift.mjs@@ -0,0 +1,1421 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Compare a documented prop table with the props the TypeScript source+ * declares for the export it describes.+ *+ * 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.+ *+ * 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:+ * - `not_in_code`: a documented prop the props type does not have (a+ * `data-*`-style name an index signature accepts counts as present);+ * - `not_in_doc`: a prop the package's own source declares, or builds with a+ * mapped type from its own keys, that the table does not list. Props from+ * outside the package (React, the DOM, another package's types or keys) are+ * never required, and neither are `className`, `style`, `xstyle`,+ * `data-testid`, `ref`, `key`, or a prop whose declaration carries an+ * `internal` JSDoc tag;+ * - `required_mismatch`: `required` disagrees with whether every caller must+ * pass the prop (one only some members of the props type require, or that+ * the package's `defaultProps` fills, is optional, as it is to JSX+ * 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.+ * @output A PropDriftReport.+ * @position Foundation discovery: it reads the package's TypeScript and+ * returns a report, and prints nothing itself.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {readPackageTsconfig} from './package-tsconfig.mjs';+import {+ resolveProjectTypeScript,+ unusableTypeScriptReason,+} from './project-typescript.mjs';+import {+ unresolvedGlobals,+ unresolvedReference,+} from './unresolved-references.mjs';++/**+ * @typedef {'not_in_code' | 'not_in_doc' | 'required_mismatch'} PropDriftKind+ */++/**+ * @typedef {object} PropDriftFinding+ * @property {string} component the documented component (export) name+ * @property {string} prop+ * @property {PropDriftKind} kind+ * @property {'warning'} severity+ * @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+ */++/**+ * @typedef {object} PropDriftUnchecked+ * @property {string} component+ * @property {string} doc the doc file, relative to the package root+ * @property {string} reason why its props could not be read+ */++/**+ * @typedef {object} PropDriftReport+ * @property {'checked' | 'skipped'} status `skipped` means nothing was+ * compared, and `reason` says why+ * @property {string} [reason]+ * @property {string} [typescript] the version of the compiler that read the props+ * @property {number} components how many documented prop tables were compared+ * @property {PropDriftFinding[]} findings+ * @property {PropDriftUnchecked[]} unchecked documented components whose props+ * could not be read from the source+ * @property {Array<PropDriftUnchecked & {props: string[]}>} [propsNotChecked]+ * props a mapped type builds from keys the check can't trace, which a doc+ * leaving out draws no warning for+ */++/**+ * @typedef {object} PropDriftTable+ * @property {string} doc the doc file, relative to the package root+ * @property {string} name the export the table documents+ * @property {any[]} props the table's entries+ * @property {string[]} sources the files that may hold the export, in order+ */++/**+ * Props a doc never needs to list: the internal and styling props the+ * `ComponentPropDoc` authoring guidance says to skip, `ref`, which Core's+ * docs also leave out, and `key`, which React keeps for itself.+ */+export const PROPS_NOT_DOCUMENTED = Object.freeze([+ 'className',+ 'style',+ 'xstyle',+ 'data-testid',+ 'ref',+ 'key',+]);++/** The guidance's internal props: a declaration tagged `@internal`. */+const SKIP_TAGS = new Set(['internal']);++/** 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.';++/** @type {WeakMap<Function, (file: string) => boolean>} */+const MINE = new WeakMap();++/**+ * Whose type names the walk checks: the package's own files and any that+ * aren't a dependency's. The same test for the same own-file test.+ * @param {(file: string) => boolean} isOwnFile+ */+function mineFor(isOwnFile) {+ let mine = MINE.get(isOwnFile);+ if (!mine) {+ mine = (/** @type {string} */ file) =>+ isOwnFile(file) || !/[\\/]node_modules[\\/]/.test(file);+ MINE.set(isOwnFile, mine);+ }+ return mine;+}++/**+ * A memoized "is this file part of the package's own source?" test.+ * @param {string} root realpath of the package root+ */+function ownFileTest(root) {+ /** @type {Map<string, boolean>} */+ const cache = new Map();+ return (/** @type {string} */ file) => {+ let own = cache.get(file);+ if (own !== undefined) return own;+ let real = file;+ try {+ real = fs.realpathSync(file);+ } catch {+ // A lib or virtual file: compare as given.+ }+ const rel = path.relative(root, real);+ own =+ rel !== '' &&+ !rel.startsWith('..') &&+ !path.isAbsolute(rel) &&+ !rel.split(path.sep).includes('node_modules');+ cache.set(file, own);+ return own;+ };+}++/**+ * @typedef {object} CodeProp+ * @property {string} name+ * @property {boolean} required whether every caller must pass it: false+ * when a member of the props type, an overload, or the package's+ * `defaultProps` lets a caller leave it out+ * @property {boolean} own declared in the package's own source, or built+ * 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 {() => any[]} types the prop's type in each member of the props type+ */++/**+ * Read the props of one export.+ * @param {any} ts+ * @param {any} program+ * @param {any} checker+ * @param {string} sourcePath+ * @param {string} exportName+ * @param {(file: string) => boolean} isOwnFile+ * @param {import('./unresolved-references.mjs').UnresolvedReference | null} ambient+ * what the program's other roots cannot resolve, which any component may+ * use+ * @returns {{ok: true, props: Map<string, CodeProp>, accepts: (name: string) => boolean} | {ok: false, reason: string}}+ */+function readCodeProps(+ ts,+ program,+ checker,+ sourcePath,+ exportName,+ isOwnFile,+ ambient,+) {+ const sourceFile = program.getSourceFile(sourcePath);+ const sourceName = path.basename(sourcePath);+ if (!sourceFile) {+ return {ok: false, reason: `the compiler could not read ${sourceName}`};+ }+ const moduleSymbol = checker.getSymbolAtLocation(sourceFile);+ const exports = moduleSymbol ? checker.getExportsOfModule(moduleSymbol) : [];+ const stem = sourceName.replace(/\.[cm]?[jt]sx?$/, '');+ let symbol =+ exports.find(/** @param {any} s */ s => s.name === exportName) ??+ (stem === exportName+ ? exports.find(/** @param {any} s */ s => s.name === 'default')+ : undefined);+ if (!symbol) {+ return {+ ok: false,+ reason: `${sourceName} has no export named ${exportName}`,+ };+ }+ if (symbol.flags & ts.SymbolFlags.Alias) {+ symbol = checker.getAliasedSymbol(symbol);+ }+ // An import that does not resolve, in the files the component comes from,+ // can make any part of its props a guess, whatever the code looks like.+ // Some TypeScript versions read such a name as a plain `any`, so this comes+ // first.+ const own = [sourceFile, ...(symbol.declarations ?? [])]+ .map(/** @param {any} n */ n => n.getSourceFile())+ .filter(/** @param {any} sf */ sf => isOwnFile(sf.fileName));+ // Type names are checked in the files that aren't a dependency's. One+ // test per run, so the walk reads each file once for every component.+ const mine = mineFor(isOwnFile);+ const found = unresolvedReference(+ ts,+ program,+ checker,+ own,+ () => true,+ mine,+ );+ // A reference that doesn't resolve names what to install; a type the+ // compiler can't give in the component's own files may only show a broken+ // global one.+ const missing = found && found.how !== 'used' ? found : (ambient ?? found);+ if (missing) {+ const where =+ path.relative(path.dirname(sourcePath), missing.file) || sourceName;+ return {+ ok: false,+ reason:+ missing.how === 'used'+ ? `${exportName} depends on ${missing.name} (used in ${where}), a type the compiler can't work out, so its props would be a guess. Check that the package's dependencies are installed and its types compile, then run this check again`+ : `${exportName} depends on ${missing.name} (${missing.how} in ${where}), which the compiler could not resolve, usually a dependency that is not installed. Install the package's dependencies and run this check again`,+ };+ }+ const type = checker.getTypeOfSymbolAtLocation(symbol, sourceFile);+ // Each member of a union (`ComponentType<P>`: a class or a function).+ const signatures = (type.isUnion() ? type.types : [type]).flatMap(+ /** @param {any} t */ t => [+ ...t.getCallSignatures(),+ ...t.getConstructSignatures(),+ ],+ );+ if (signatures.length === 0) {+ // An `any` the source does not write comes from a type that does not+ // resolve, such as `forwardRef` when React's types are not installed.+ const writtenAny =+ symbol.valueDeclaration?.type?.kind === ts.SyntaxKind.AnyKeyword;+ const unresolved =+ !writtenAny &&+ (type.flags & ts.TypeFlags.Any ||+ hasUnresolvedPart(ts, checker, type, 0, new Set()));+ return {+ ok: false,+ reason: unresolved+ ? `${exportName}'s own type includes a type the compiler could not resolve, usually an import whose package is not installed (such as React's types, for a forwardRef or memo component). Install the package's dependencies and run this check again`+ : writtenAny+ ? `${exportName} is typed \`any\`, so it has no props to compare`+ : `${exportName} in ${sourceName} is not a component (it cannot be called with props)`,+ };+ }+ const unresolved = {+ ok: /** @type {const} */ (false),+ reason: `${exportName}'s props type includes a type the compiler could not resolve, usually an import whose package is not installed. Install the package's dependencies and run this check again`,+ };+ // Every overload: its props type joins the others as a member, as a+ // union's members do. An overload that takes no props makes every prop+ // optional.+ /** @type {any[]} */+ const propsTypes = [];+ let propless = false;+ for (const signature of signatures) {+ const parameter = signature.getParameters()[0];+ if (parameter) {+ propsTypes.push(checker.getTypeOfSymbolAtLocation(parameter, sourceFile));+ } else {+ propless = true;+ }+ }+ /** @type {Map<string, CodeProp>} */+ const props = new Map();+ if (propsTypes.length === 0) return {ok: true, props, accepts: () => false};++ // Props that are `any`, written so or made from it (`FC<any>`, or+ // `forwardRef<E, any>`'s `Omit<any, 'ref'>`).+ if (propsTypes.some(propsType => isAnyProps(ts, checker, propsType))) {+ return {+ ok: false,+ reason: `${exportName}'s props are typed \`any\`, so there is nothing to compare them with`,+ };+ }+ if (+ propsTypes.some(propsType =>+ hasUnresolvedPart(ts, checker, propsType, 0, new Set()),+ )+ ) {+ return unresolved;+ }++ const members = propsTypes+ .flatMap(propsType => (propsType.isUnion() ? propsType.types : [propsType]))+ .filter(+ /** @param {any} t */+ t => !(t.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Null)),+ );+ // A generic component whose props take their names from a type parameter+ // (the element it renders: `Omit<ComponentPropsWithoutRef<E>, 'as'>`, or a+ // bare `props: P`) accepts names that are known only where it is used.+ const generic = signatures.some(+ /** @param {any} signature */ signature =>+ (signature.getTypeParameters?.() ?? []).length > 0,+ );+ // Props that refer to a type parameter and show the compiler no members+ // at all would draw a finding for every documented name: listed too.+ const unnamed =+ members.some(member => isDeferred(ts, checker, member, true)) &&+ members.every(+ member =>+ checker.getPropertiesOfType(member).length === 0 &&+ (checker.getIndexInfosOfType?.(member) ?? []).length === 0,+ );+ if (+ generic &&+ (unnamed ||+ members.some(member => namesFromTypeParameter(ts, checker, member, 0)))+ ) {+ return {+ ok: false,+ 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`,+ };+ }+ // `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+ // out; `any` fills every prop. React's own types declare an optional one on+ // every component type.+ let holder = type;+ for (let i = 0; i < 2 && checker.getPropertyOfType(holder, '$$typeof'); i++) {+ const inner =+ checker.getPropertyOfType(holder, 'type') ??+ checker.getPropertyOfType(holder, '_result');+ if (!inner) break;+ holder = checker.getTypeOfSymbolAtLocation(inner, sourceFile);+ }+ const defaultProps = checker.getPropertyOfType(holder, 'defaultProps');+ const defaults = defaultProps?.declarations?.some(+ /** @param {any} d */ d => isOwnFile(d.getSourceFile().fileName),+ )+ ? checker.getTypeOfSymbolAtLocation(defaultProps, sourceFile)+ : null;+ const fillsAll = !!defaults && !!(defaults.flags & ts.TypeFlags.Any);+ const defaulted = new Set(+ defaults+ ? checker+ .getPropertiesOfType(defaults)+ .map(/** @param {any} s */ s => s.name)+ : [],+ );++ /** @type {Map<string, {symbols: any[], optional: number}>} */+ const byName = new Map();+ for (const member of members) {+ for (const prop of checker.getPropertiesOfType(member)) {+ const entry = byName.get(prop.name) ?? {symbols: [], optional: 0};+ entry.symbols.push(prop);+ if (prop.flags & ts.SymbolFlags.Optional) entry.optional++;+ byName.set(prop.name, entry);+ }+ }+ if (fillsAll) for (const name of byName.keys()) defaulted.add(name);++ /** @type {((prop: any) => string) | undefined} */+ let origin;+ // Read from the component's declaration, its props parameter's, and the+ // wrapped component's for `memo` and `lazy`.+ const originOf = (/** @type {any} */ prop) =>+ (origin ??= mappedPropOrigin(ts, checker, isOwnFile, [+ symbol.valueDeclaration ?? symbol.declarations?.[0],+ ...[+ ...signatures,+ ...(holder === type ? [] : holder.getCallSignatures()),+ ].map(+ (/** @type {any} */ signature) =>+ signature.getParameters()[0]?.valueDeclaration,+ ),+ ]))(prop);+ for (const [name, {symbols, optional}] of byName) {+ const declarations = symbols.flatMap(+ /** @param {any} s */ s => s.declarations ?? [],+ );+ const ownDeclarations = declarations.filter(+ /** @param {any} d */ d => isOwnFile(d.getSourceFile().fileName),+ );+ // A prop no declaration names, one a mapped type builds, is the+ // package's own when its key comes from the package's own source.+ const built =+ declarations.length === 0 ? strongest(symbols.map(originOf)) : null;+ // Optional when a caller may leave it out: an overload that takes no+ // props, or a member of the props type that does not require it.+ const required =+ !defaulted.has(name) &&+ !propless &&+ symbols.length === members.length &&+ optional === 0;+ props.set(name, {+ name,+ required,+ own: ownDeclarations.length > 0 || built === 'own',+ untraced:+ declarations.length === 0 && built !== 'own' && built !== 'foreign',+ skipTagged: ownDeclarations.some(+ /** @param {any} d */+ d =>+ ts+ .getJSDocTags(d)+ .some(+ /** @param {any} tag */ tag => SKIP_TAGS.has(tag.tagName.text),+ ),+ ),+ types: () =>+ symbols.map(+ /** @param {any} s */ s =>+ checker.getTypeOfSymbolAtLocation(s, sourceFile),+ ),+ });+ }++ /** Does an index signature of the props type accept this name? */+ const accepts = (/** @type {string} */ name) =>+ members.some(+ /** @param {any} member */ member =>+ (checker.getIndexInfosOfType?.(member) ?? []).some(+ /** @param {any} info */ info =>+ !holdsNothing(ts, info.type) &&+ keyAccepts(ts, checker, info.keyType, name),+ ),+ );+ return {ok: true, props, accepts};+}++/**+ * 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+ * into as many parts); `x.y` (or+ * `x[].y`) documents a field of prop `x`; `...rest` documents a spread of+ * another props type and is not compared.+ * @param {any} raw+ * @returns {Array<{name: string, written: string, path: string[], spread: boolean, type?: string, required?: boolean}>}+ */+function documentedProps(raw) {+ const names = String(raw.name)+ .split(/\s+\/\s+/)+ .map(name => name.trim())+ .filter(Boolean);+ const types = typeof raw.type === 'string' ? raw.type.split(/\s+\/\s+/) : [];+ return names.map((written, i) => {+ const spread = written.startsWith('...');+ const [root = written, ...path] = written+ .replace(/\[\]/g, '')+ .split('.')+ .filter(Boolean);+ return {+ name: spread ? written : root,+ written,+ path: spread ? [] : path,+ spread,+ type:+ names.length === 1+ ? raw.type+ : types.length === names.length+ ? types[i]+ : undefined,+ required: raw.required,+ };+ });+}++/**+ * The types a field can sit on: each member of a union, through arrays and+ * tuples at any depth (`grid[][].id`).+ * @param {any} ts+ * @param {any} checker+ * @param {any} type+ * @param {number} [depth]+ * @returns {any[]}+ */+function holders(ts, checker, type, depth = 0) {+ if (depth > 8) return [type];+ if (type.isUnion()) {+ return type.types.flatMap(+ /** @param {any} t */ t => holders(ts, checker, t, depth + 1),+ );+ }+ const array =+ ['Array', 'ReadonlyArray'].includes(type.symbol?.name) ||+ type.target?.objectFlags & ts.ObjectFlags.Tuple;+ if (array && type.objectFlags & ts.ObjectFlags.Reference) {+ return checker+ .getTypeArguments(type)+ .flatMap(/** @param {any} t */ t => holders(ts, checker, t, depth + 1));+ }+ return [type];+}++/**+ * Does a field path exist in a prop's type, in at least one member of a+ * union (through arrays)?+ * @param {any} ts+ * @param {any} checker+ * @param {CodeProp} code+ * @param {string[]} fieldPath+ */+function fieldExists(ts, checker, code, fieldPath) {+ /** @type {any[]} */+ let current = code.types();+ for (const field of fieldPath) {+ /** @type {any[]} */+ const next = [];+ for (const holder of current.flatMap(t => holders(ts, checker, t))) {+ if (holder.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) return true;+ const prop = checker.getPropertyOfType(holder, field);+ // Or a field an index signature takes (`Record<string, string>`).+ const index = prop+ ? null+ : (checker.getIndexInfosOfType?.(holder) ?? []).find(+ /** @param {any} info */ info =>+ !holdsNothing(ts, info.type) &&+ keyAccepts(ts, checker, info.keyType, field),+ );+ if (prop) next.push(checker.getTypeOfSymbol(prop));+ else if (index) next.push(index.type);+ }+ if (next.length === 0) return false;+ current = next;+ }+ return true;+}++/**+ * Is a type the compiler's stand-in for a name it could not resolve?+ * @param {any} ts+ * @param {any} type+ */+function isErrorType(ts, type) {+ return (+ (type.flags & ts.TypeFlags.Any) !== 0 && type.intrinsicName === 'error'+ );+}++/**+ * Do some of a generic component's prop names come from a type parameter:+ * a deferred type, an index signature keyed or valued by a type made from+ * one, or a mapped type whose keys are one (`Partial<P>`) or whose `as`+ * clause uses one? An interface whose values alone use it (`ListProps<T>`),+ * a mapping over keys of its own (`Record<'value', V>`), and an index that+ * takes any name (`[key: string]: any`) give names of its own.+ * @param {any} ts+ * @param {any} checker+ * @param {any} type+ * @param {number} depth+ * @returns {boolean}+ */+function namesFromTypeParameter(ts, checker, type, depth) {+ if (depth > 8) return false;+ if (type.isUnion() || type.isIntersection()) {+ return type.types.some(+ /** @param {any} t */ t =>+ namesFromTypeParameter(ts, checker, t, depth + 1),+ );+ }+ if (isDeferred(ts, checker, type)) return true;+ if (+ (checker.getIndexInfosOfType?.(type) ?? []).some(+ /** @param {any} info */ info =>+ isDeferred(ts, checker, info.type, true) ||+ isDeferred(ts, checker, info.keyType, true),+ )+ ) {+ return true;+ }+ if ((type.objectFlags & ts.ObjectFlags.Mapped) === 0) return false;+ // The keys, which the compiler works out when it reads the members.+ checker.getPropertiesOfType(type);+ return (+ (!!type.constraintType && isDeferred(ts, checker, type.constraintType)) ||+ renamedByTypeParameter(ts, checker, type)+ );+}++/**+ * Does a mapping's `as` clause use a type parameter besides its own key that+ * is still open where the props are read: one the component declares, or one+ * an alias passes on whose argument is still a type parameter (`` as+ * `${N}${K}` ``, `as T extends true ? K : never`)? Given fixed arguments+ * (`Prefixed<'my'>`, a key filter such as `Except<Props, 'b'>`), every key+ * gets its name. Its own key, and an `infer` inside the clause, are known+ * for each key.+ * @param {any} ts+ * @param {any} checker+ * @param {any} type a mapped type+ * @returns {boolean}+ */+function renamedByTypeParameter(ts, checker, type) {+ const clause = type.declaration?.nameType;+ if (!clause) return false;+ /** @type {(node: any) => boolean} */+ const uses = node => {+ const symbol = ts.isTypeReferenceNode(node)+ ? checker.getSymbolAtLocation(node.typeName)+ : undefined;+ const declaration =+ symbol && symbol.flags & ts.SymbolFlags.TypeParameter+ ? symbol.declarations?.[0]+ : undefined;+ const inClause =+ declaration?.getSourceFile() === clause.getSourceFile() &&+ declaration.pos >= clause.pos &&+ declaration.end <= clause.end;+ if (+ declaration &&+ declaration !== type.declaration.typeParameter &&+ !inClause+ ) {+ // Its value where the props are read, through the instantiation.+ const value = valueIn(+ ts,+ checker,+ checker.getDeclaredTypeOfSymbol(symbol),+ type.mapper,+ 0,+ );+ if (!value || isDeferred(ts, checker, value, true)) return true;+ }+ return !!ts.forEachChild(+ node,+ /** @param {any} child */ child => uses(child) || undefined,+ );+ };+ return uses(clause);+}++/**+ * The value an instantiation gives a type parameter, as the compiler's own+ * mappers give it, through each mapper one combines; null when that takes+ * more than following parameters (a value made from one, or a mapper of+ * another form), which counts as open.+ * @param {any} ts+ * @param {any} checker+ * @param {any} parameter+ * @param {any} mapper+ * @param {number} depth+ * @returns {any}+ */+function valueIn(ts, checker, parameter, mapper, depth) {+ if (!mapper) return parameter;+ if (depth > 32) return null;+ if (mapper.mapper1 && mapper.mapper2) {+ const first = valueIn(ts, checker, parameter, mapper.mapper1, depth + 1);+ if (!first) return null;+ if (first === parameter || first.flags & ts.TypeFlags.TypeParameter) {+ return valueIn(ts, checker, first, mapper.mapper2, depth + 1);+ }+ return isDeferred(ts, checker, first, true) ? null : first;+ }+ if ('source' in mapper) {+ return mapper.source === parameter ? mapper.target : parameter;+ }+ if (Array.isArray(mapper.sources)) {+ const i = mapper.sources.indexOf(parameter);+ if (i < 0) return parameter;+ const target = mapper.targets?.[i];+ return typeof target === 'function' ? target() : (target ?? null);+ }+ return typeof mapper.func === 'function' ? mapper.func(parameter) : null;+}++/**+ * A type parameter, or a type the compiler defers until one is known (an+ * indexed access, a conditional), or a union, intersection or template+ * literal with one (`on${K}`, `Capitalize<K>`); with `deep`, also a type made+ * from one (through alias or reference arguments).+ * @param {any} ts+ * @param {any} checker+ * @param {any} t+ * @param {boolean} [deep]+ * @param {number} [depth]+ * @returns {boolean}+ */+function isDeferred(ts, checker, t, deep = false, depth = 0) {+ const F = ts.TypeFlags;+ if (+ t.flags &+ (F.TypeParameter |+ F.IndexedAccess |+ F.Conditional |+ F.Substitution |+ F.Index)+ ) {+ return true;+ }+ if (depth > 6) return false;+ const parts = [+ ...(t.isUnion() || t.isIntersection() ? t.types : []),+ ...(t.flags & F.TemplateLiteral ? (t.types ?? []) : []),+ ...(t.flags & F.StringMapping && t.type ? [t.type] : []),+ ...(deep ? (t.aliasTypeArguments ?? []) : []),+ ...(deep && t.objectFlags & ts.ObjectFlags.Reference+ ? checker.getTypeArguments(t)+ : []),+ ];+ return parts.some(u => isDeferred(ts, checker, u, deep, depth + 1));+}++/**+ * Does an index signature's key take this prop name, as TypeScript would? A+ * `string` key takes any name; a template literal key only the names that+ * match it (`data-${string}`, `col${number}`, `on${Capitalize<string>}`).+ * @param {any} ts+ * @param {any} checker+ * @param {any} key+ * @param {string} name+ */+function keyAccepts(ts, checker, key, name) {+ if (key.flags & ts.TypeFlags.String) return true;+ if (!(key.flags & ts.TypeFlags.TemplateLiteral)) return false;+ if (checker.getStringLiteralType && checker.isTypeAssignableTo) {+ return checker.isTypeAssignableTo(checker.getStringLiteralType(name), key);+ }+ // An older TypeScript has no literal-type factory: match the template.+ /** @type {Record<string, string>} */+ const mappings = {+ Uppercase: '[^a-z]*',+ Lowercase: '[^A-Z]*',+ Capitalize: '(?:[^a-z][\\s\\S]*)?',+ Uncapitalize: '(?:[^A-Z][\\s\\S]*)?',+ };+ const spans = (key.types ?? []).map(+ /** @param {any} span */ span =>+ span.flags & ts.TypeFlags.Number+ ? '[-+]?(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][-+]?\\d+)?'+ : (mappings[String(span.symbol?.escapedName)] ?? '[\\s\\S]*'),+ );+ const pattern = (key.texts ?? [])+ .map(+ (/** @type {string} */ text, /** @type {number} */ i) =>+ text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + (spans[i] ?? ''),+ )+ .join('');+ return new RegExp(`^${pattern}$`).test(name);+}++/**+ * Can a value of this type be passed at all? `never`, or only `undefined`+ * (`Record<string, never>`, the usual way to write "no props"), cannot.+ * @param {any} ts+ * @param {any} type+ */+function holdsNothing(ts, type) {+ const parts = type.isUnion() ? type.types : [type];+ return parts.every(+ /** @param {any} t */ t =>+ t.flags & (ts.TypeFlags.Never | ts.TypeFlags.Undefined),+ );+}++/** @param {Array<string | null>} found the answers for one key, by place */+const strongest = found =>+ ['own', 'foreign', 'unknown'].find(answer => found.includes(answer)) ?? null;++/**+ * Where the key of a prop a mapped type builds, which no declaration names,+ * comes from: `own` when the package's own source writes it, as a literal or+ * a property's declaration, `foreign` when another package's types do, and+ * `unknown` when the check can't trace it. It reads the mapping where the+ * component's declaration and props parameter reach it (and the component a+ * `memo`, `lazy` or `forwardRef` call wraps), through aliases, a generic's+ * arguments, `keyof`, `typeof`, and a conditional's branches (`Exclude`,+ * `Extract`).+ * @param {any} ts+ * @param {any} checker+ * @param {(file: string) => boolean} isOwnFile+ * @param {any[]} starts+ * @returns {(prop: any) => string}+ */+function mappedPropOrigin(ts, checker, isOwnFile, starts) {+ /** @type {Map<any, Map<any, any>[]>} each mapping, with its type arguments */+ const sites = new Map();+ let budget = 5000;+ /** @param {any} node */+ const where = node =>+ isOwnFile(node.getSourceFile().fileName) ? 'own' : 'foreign';+ /** @param {any} node */+ const target = node => {+ let symbol = checker.getSymbolAtLocation(+ node.typeName ?? node.exprName ?? node.expression ?? node,+ );+ if (symbol && symbol.flags & ts.SymbolFlags.Alias) {+ symbol = checker.getAliasedSymbol(symbol);+ }+ return symbol;+ };+ /** @type {(params: any, args: any, env: Map<any, any>) => Map<any, any>} */+ const bind = (params, args, env) => {+ const next = new Map(env);+ (params ?? []).forEach(+ (/** @type {any} */ param, /** @type {number} */ i) => {+ const node = args?.[i] ?? param.default;+ if (node)+ next.set(target(param.name), {node, env: args?.[i] ? env : next});+ },+ );+ return next;+ };+ /** @type {(node: any, env: Map<any, any>, depth: number) => void} */+ const visit = (node, env, depth) => {+ if (!node || depth > 40 || budget-- <= 0) return;+ if (ts.isMappedTypeNode(node)) {+ sites.set(node, [...(sites.get(node) ?? []), env]);+ }+ const reference =+ ts.isTypeReferenceNode(node) || ts.isExpressionWithTypeArguments(node);+ // A component another binding wraps: `memo(Inner)`, `forwardRef(Impl)`.+ const wrapped =+ ts.isIdentifier(node) &&+ (ts.isCallExpression(node.parent) ||+ ts.isVariableDeclaration(node.parent)) &&+ node !== node.parent.expression &&+ node !== node.parent.name;+ for (const declaration of reference || wrapped+ ? (target(node)?.declarations ?? [])+ : []) {+ const own = where(declaration) === 'own';+ if (reference && ts.isTypeAliasDeclaration(declaration)) {+ visit(+ declaration.type,+ bind(declaration.typeParameters, node.typeArguments, env),+ depth + 1,+ );+ } else if (reference && (own || !node.typeArguments)) {+ // Another package's interface: only what it extends.+ const next = bind(declaration.typeParameters, node.typeArguments, env);+ if (own) visit(declaration, next, depth + 1);+ else+ for (const clause of declaration.heritageClauses ?? [])+ visit(clause, next, depth + 1);+ } else if (wrapped && own) {+ visit(declaration, env, depth + 1);+ }+ }+ ts.forEachChild(node, (/** @type {any} */ child) =>+ visit(child, env, depth + 1),+ );+ };+ /** @type {(node: any, key: string, env: Map<any, any>, depth: number) => string | null} */+ const keyOrigin = (node, key, env, depth) => {+ if (!node || depth > 40) return 'unknown';+ const next = (/** @type {any} */ inner) =>+ keyOrigin(inner, key, env, depth + 1);+ if (ts.isParenthesizedTypeNode(node)) return next(node.type);+ if (ts.isLiteralTypeNode(node)) {+ return node.literal.text === key ? where(node) : null;+ }+ if (ts.isUnionTypeNode(node)) return strongest(node.types.map(next));+ if (ts.isConditionalTypeNode(node)) {+ return strongest([next(node.trueType), next(node.falseType)]);+ }+ if (+ ts.isTypeOperatorNode(node) &&+ node.operator === ts.SyntaxKind.KeyOfKeyword+ ) {+ const of =+ ts.isTypeReferenceNode(node.type) && env.get(target(node.type));+ const prop = checker.getPropertyOfType(+ checker.getTypeFromTypeNode(of ? of.node : node.type),+ key,+ );+ return prop ? propOrigin(prop, depth + 1) : null;+ }+ if (ts.isArrayTypeNode(node)) return next(node.elementType);+ if (ts.isTupleTypeNode(node)) return strongest(node.elements.map(next));+ if (ts.isTypeOperatorNode(node)) return next(node.type);+ if (ts.isIndexedAccessTypeNode(node)) {+ // `Props['size']` reads the property's own type; `(typeof SIZES)[number]`+ // reads the value's.+ const index = ts.isLiteralTypeNode(node.indexType)+ ? node.indexType.literal.text+ : undefined;+ if (index === undefined) return next(node.objectType);+ const declared = checker.getPropertyOfType(+ checker.getTypeFromTypeNode(node.objectType),+ index,+ )?.declarations?.[0];+ return declared ? valueOrigin(declared, key, depth + 1) : 'unknown';+ }+ if (ts.isTypeQueryNode(node)) {+ return valueOrigin(target(node)?.valueDeclaration, key, depth + 1);+ }+ if (ts.isTypeReferenceNode(node)) {+ const symbol = target(node);+ const bound = symbol && env.get(symbol);+ if (bound) return keyOrigin(bound.node, key, bound.env, depth + 1);+ const alias = symbol?.declarations?.find(ts.isTypeAliasDeclaration);+ if (alias) {+ return keyOrigin(+ alias.type,+ key,+ bind(alias.typeParameters, node.typeArguments, env),+ depth + 1,+ );+ }+ // An enum: where it is declared. A type parameter no argument binds,+ // such as an `infer`, can't be traced.+ if (+ symbol &&+ symbol.flags & (ts.SymbolFlags.Enum | ts.SymbolFlags.EnumMember)+ ) {+ return where(symbol.declarations[0]);+ }+ }+ return 'unknown';+ };+ /**+ * Where a value's literal keys are written: its declared type, or the+ * literals its initializer writes, through `as const` and other bindings.+ * @type {(node: any, key: string, depth: number) => string | null}+ */+ const valueOrigin = (node, key, depth) => {+ if (!node || depth > 40) return 'unknown';+ if (ts.isStringLiteralLike(node) || ts.isNumericLiteral(node)) {+ return node.text === key ? where(node) : null;+ }+ if (ts.isArrayLiteralExpression(node)) {+ return strongest(+ node.elements.map((/** @type {any} */ e) =>+ valueOrigin(e, key, depth + 1),+ ),+ );+ }+ // A declared type or a cast, but not `as const` or `satisfies`.+ const written =+ node.type &&+ !ts.isSatisfiesExpression?.(node) &&+ node.type.typeName?.text !== 'const';+ if (written) return keyOrigin(node.type, key, new Map(), depth + 1);+ const inner = node.initializer ?? node.expression;+ if (inner) return valueOrigin(inner, key, depth + 1);+ if (ts.isIdentifier(node)) {+ let symbol = checker.getSymbolAtLocation(node);+ if (symbol && symbol.flags & ts.SymbolFlags.Alias) {+ symbol = checker.getAliasedSymbol(symbol);+ }+ return valueOrigin(symbol?.valueDeclaration, key, depth + 1);+ }+ return 'unknown';+ };+ /** @type {(prop: any, depth: number) => string | null} */+ const propOrigin = (prop, depth) => {+ if (depth > 40) return 'unknown';+ const declarations = prop.declarations ?? [];+ if (declarations.length > 0) {+ return declarations.some((/** @type {any} */ d) => where(d) === 'own')+ ? 'own'+ : 'foreign';+ }+ const links = prop.links ?? prop;+ if (links.syntheticOrigin)+ return propOrigin(links.syntheticOrigin, depth + 1);+ if (links.containingType) {+ return strongest(+ links.containingType.types.map((/** @type {any} */ t) => {+ const part = checker.getPropertyOfType(t, prop.name);+ return part && part !== prop ? propOrigin(part, depth + 1) : null;+ }),+ );+ }+ const mapping = links.mappedType?.declaration;+ const key = links.keyType?.value;+ if (!mapping || key === undefined) return 'unknown';+ return strongest(+ (sites.get(mapping) ?? []).map(env =>+ keyOrigin(+ mapping.typeParameter.constraint,+ String(key),+ env,+ depth + 1,+ ),+ ),+ );+ };+ for (const start of starts) {+ if (start && where(start) === 'own') visit(start, new Map(), 0);+ }+ return prop => propOrigin(prop, 0) ?? 'unknown';+}++/**+ * Are props `any`: a plain `any` (not one standing for a name that does not+ * resolve), or a type an alias makes from `any` by reading its keys, which+ * takes every name (`Omit<any, 'ref'>`, or React's `Omit` of one)? `Record<string, any>` only gives+ * names an `any` value, as an inline `[key: string]: any` does.+ * @param {any} ts+ * @param {any} checker+ * @param {any} type+ * @param {number} [depth] how far into an alias's arguments+ * @returns {boolean}+ */+function isAnyProps(ts, checker, type, depth = 0) {+ if (type.flags & ts.TypeFlags.Any) return !isErrorType(ts, type);+ const parts = type.isUnion() || type.isIntersection() ? type.types : [type];+ /** @type {(node: any) => any} the symbol a reference names */+ const target = node => {+ const used = checker.getSymbolAtLocation(node.typeName ?? node.expression);+ return used && used.flags & ts.SymbolFlags.Alias+ ? checker.getAliasedSymbol(used)+ : used;+ };+ /** @type {(node: any) => any} */+ const aliasOf = node =>+ target(node)?.declarations?.find(ts.isTypeAliasDeclaration);+ // Whether an alias reads its `i`th parameter's keys: `keyof T`, or `T`+ // passed on to an alias that does, as `type Without<T> = Omit<T, 'as'>`.+ /** @type {(alias: any, i: number, depth?: number) => boolean} */+ const readsKeys = (alias, i, depth = 0) => {+ const name = alias?.typeParameters?.[i]?.name.text;+ /** @type {(node: any) => boolean} */+ const visit = node =>+ (ts.isTypeOperatorNode(node) &&+ node.operator === ts.SyntaxKind.KeyOfKeyword &&+ node.type.typeName?.text === name) ||+ (ts.isTypeReferenceNode(node) &&+ depth < 8 &&+ (node.typeArguments ?? []).some(+ (/** @type {any} */ arg, /** @type {number} */ j) =>+ arg.typeName?.text === name &&+ readsKeys(aliasOf(node), j, depth + 1),+ )) ||+ !!ts.forEachChild(+ node,+ (/** @type {any} */ child) => visit(child) || undefined,+ );+ return !!name && visit(alias);+ };+ /** @type {(symbol: any) => any[]} an alias's type, or an interface's bases */+ const shapeOf = symbol =>+ (symbol?.declarations ?? []).flatMap((/** @type {any} */ d) =>+ ts.isTypeAliasDeclaration(d)+ ? [d.type]+ : (d.heritageClauses?.flatMap((/** @type {any} */ c) => c.types) ?? []),+ );+ // `any`, or such a type, passed where an alias reads its keys, written in+ // the props type or one of the package's names for it (`type P =+ // Without<any>`, `interface P extends Omit<Omit<any, 'as'>, 'ref'>`).+ /** @type {(node: any, depth: number) => boolean} */+ const anyKeyed = (node, depth) => {+ if (!node || depth > 8) return false;+ if (node.kind === ts.SyntaxKind.AnyKeyword) return true;+ if (ts.isParenthesizedTypeNode(node)) return anyKeyed(node.type, depth + 1);+ if (ts.isUnionTypeNode(node) || ts.isIntersectionTypeNode(node)) {+ return node.types.some((/** @type {any} */ t) => anyKeyed(t, depth + 1));+ }+ // A reference: `Name<…>`, or an interface's `extends Name<…>`.+ if (!node.typeName && !node.expression) return false;+ const alias = aliasOf(node);+ return node.typeArguments+ ? node.typeArguments.some(+ (/** @type {any} */ arg, /** @type {number} */ i) =>+ anyKeyed(arg, depth + 1) && readsKeys(alias, i),+ )+ : shapeOf(target(node)).some(n => anyKeyed(n, depth + 1));+ };+ return parts.some(+ /** @param {any} part */ part =>+ ((part.aliasTypeArguments ?? []).some(+ /** @type {(t: any, i: number) => boolean} */ (t, i) =>+ (t.flags & ts.TypeFlags.Any+ ? !isErrorType(ts, t)+ : depth < 4 && isAnyProps(ts, checker, t, depth + 1)) &&+ readsKeys(part.aliasSymbol?.declarations?.[0], i),+ ) ||+ shapeOf(part.aliasSymbol ?? part.symbol).some(n => anyKeyed(n, 0))) &&+ (checker.getIndexInfosOfType?.(part) ?? []).some(+ /** @param {any} info */ info => info.type.flags & ts.TypeFlags.Any,+ ),+ );+}++/**+ * Is any part of a props type `any`, or built from a type the compiler could+ * not resolve (`Omit<Missing, 'x'>`, `Partial<Missing>`)? Then props it would+ * inherit are missing or unknown, and comparing would report documented+ * props as absent, or pass them unread.+ * @param {any} ts+ * @param {any} checker+ * @param {any} type+ * @param {number} depth+ * @param {Set<any>} seen types already read, so shared bases are read once+ * @returns {boolean}+ */+function hasUnresolvedPart(ts, checker, type, depth, seen) {+ if (depth > 24 || seen.has(type)) return false;+ seen.add(type);+ if (type.flags & ts.TypeFlags.Any) return true;+ // A type made from another keeps what it was made from: an alias its+ // arguments, a generic reference its type arguments.+ const made = [+ ...(type.aliasTypeArguments ?? []),+ ...(type.objectFlags & ts.ObjectFlags.Reference+ ? checker.getTypeArguments(type)+ : []),+ ];+ if (made.some(/** @param {any} t */ t => isErrorType(ts, t))) return true;+ // A mapped type over one that does not resolve keeps no arguments behind a+ // named alias (`type Base = Pick<Missing, 'title'>`): its properties have+ // the compiler's error type.+ if (+ type.objectFlags & ts.ObjectFlags.Mapped &&+ checker+ .getPropertiesOfType(type)+ .some(+ /** @param {any} p */ p => isErrorType(ts, checker.getTypeOfSymbol(p)),+ )+ ) {+ return true;+ }+ // A mapped type written over one that does not resolve+ // (`{[K in keyof Missing]?: string}`) keeps it only in its declaration.+ const constraint = type.declaration?.typeParameter?.constraint;+ const mappedOver =+ constraint && ts.isTypeOperatorNode(constraint)+ ? constraint.type+ : constraint;+ if (+ type.objectFlags & ts.ObjectFlags.Mapped &&+ mappedOver &&+ isErrorType(ts, checker.getTypeFromTypeNode(mappedOver))+ ) {+ return true;+ }+ // A type mapped over one that does not resolve (`Omit<Missing, 'x'>`,+ // `Partial<Missing>`), reached directly, through a named alias, or nested,+ // reads as index signatures whose value is that unresolved type, which no+ // source declares.+ if (+ type.flags & ts.TypeFlags.Object &&+ (checker.getIndexInfosOfType?.(type) ?? []).some(+ /** @param {any} info */ info =>+ !info.declaration && isErrorType(ts, info.type),+ )+ ) {+ return true;+ }+ if (type.isUnion() || type.isIntersection()) {+ return type.types.some(+ /** @param {any} t */ t =>+ hasUnresolvedPart(ts, checker, t, depth + 1, seen),+ );+ }+ if (type.flags & ts.TypeFlags.Object) {+ const target =+ type.objectFlags & ts.ObjectFlags.Reference ? type.target : type;+ if (target.objectFlags & ts.ObjectFlags.ClassOrInterface) {+ // An unresolved `extends` is dropped from the base types, so read the+ // heritage clauses themselves.+ for (const declaration of target.symbol?.declarations ?? []) {+ for (const clause of declaration.heritageClauses ?? []) {+ for (const node of clause.types) {+ const base = checker.getTypeAtLocation(node);+ if (hasUnresolvedPart(ts, checker, base, depth + 1, seen))+ return true;+ }+ }+ }+ }+ }+ return false;+}++/**+ * Compare each documented prop table with the TypeScript props of the export+ * it describes.+ * @param {PropDriftTable[]} tables+ * @param {{packageDir: string, resolveFrom: Array<string | null | undefined>}} options+ * @returns {PropDriftReport}+ */+export function comparePropTables(tables, options) {+ const {packageDir, resolveFrom} = options;+ const compiler = resolveProjectTypeScript(resolveFrom);+ if (!compiler?.ts) {+ return {+ status: 'skipped',+ reason: compiler+ ? unusableTypeScriptReason(+ compiler.version,+ 'documented props were not compared with the code',+ )+ : TYPESCRIPT_MISSING_REASON,+ components: 0,+ findings: [],+ unchecked: [],+ };+ }+ const {ts, version} = compiler;+ let root = path.resolve(packageDir);+ try {+ root = fs.realpathSync(root);+ } catch {+ // Keep the resolved path.+ }+ const rel = (/** @type {string} */ file) =>+ path.relative(packageDir, file).split(path.sep).join('/');++ /** @type {PropDriftUnchecked[]} */+ const unchecked = [];+ if (tables.length === 0) {+ return {+ status: 'checked',+ typescript: version,+ components: 0,+ findings: [],+ unchecked,+ };+ }++ const project = readPackageTsconfig(+ ts,+ packageDir,+ tables.flatMap(table => table.sources),+ );+ if (project.error) {+ // Read without the package's own config, the types would be guesses.+ for (const table of tables) {+ unchecked.push({+ component: table.name,+ doc: table.doc,+ reason: `the package's TypeScript config has an error, so props were not read (${project.error})`,+ });+ }+ unchecked.sort((a, b) => a.component.localeCompare(b.component));+ return {+ status: 'checked',+ typescript: version,+ components: 0,+ findings: [],+ unchecked,+ };+ }+ const program = ts.createProgram({+ rootNames: [+ ...new Set([+ ...tables.flatMap(table => table.sources),+ ...project.declarations,+ ]),+ ],+ options: project.options,+ });+ const checker = program.getTypeChecker();+ const isOwnFile = ownFileTest(root);+ const ambient = unresolvedGlobals(+ ts,+ program,+ checker,+ project.declarations,+ project.options,+ isOwnFile,+ );++ /** @type {PropDriftFinding[]} */+ const findings = [];+ /** @type {Array<PropDriftUnchecked & {props: string[]}>} */+ const propsNotChecked = [];+ let compared = 0;+ for (const table of tables) {+ /** @type {ReturnType<typeof readCodeProps> | null} */+ let read = null;+ let sourcePath = table.sources[0];+ for (const candidate of table.sources) {+ const attempt = readCodeProps(+ ts,+ program,+ checker,+ candidate,+ table.name,+ isOwnFile,+ ambient,+ );+ if (attempt.ok || read == null) {+ read = attempt;+ sourcePath = candidate;+ }+ if (attempt.ok) break;+ }+ if (read == null || !read.ok) {+ unchecked.push({+ component: table.name,+ doc: table.doc,+ reason:+ read != null && !read.ok+ ? read.reason+ : `no source file for ${table.name}`,+ });+ continue;+ }+ compared++;+ const source = rel(sourcePath);+ const documented = new Set();+ for (const raw of table.props) {+ if (!raw || typeof raw.name !== 'string') continue;+ const entries = documentedProps(raw);+ for (const entry of entries) {+ const propName = entry.name;+ if (entry.spread) continue;+ documented.add(propName);+ const code = read.props.get(propName);+ const base = {+ component: table.name,+ prop: entry.written,+ severity: /** @type {const} */ ('warning'),+ doc: table.doc,+ source,+ };+ if (entry.path.length > 0) {+ if (+ code+ ? fieldExists(ts, checker, code, entry.path)+ : read.accepts(propName)+ ) {+ continue;+ }+ findings.push({+ ...base,+ kind: 'not_in_code',+ message: code+ ? `"${entry.written}" is documented, but ${table.name}'s "${propName}" has no "${entry.path.join('.')}".`+ : `"${entry.written}" is documented, but ${table.name}'s props have no "${propName}".`,+ });+ continue;+ }+ if (!code) {+ if (read.accepts(propName)) continue;+ findings.push({+ ...base,+ kind: 'not_in_code',+ message: `"${propName}" is documented, but ${table.name}'s props have no "${propName}".`,+ });+ continue;+ }+ const docRequired = entry.required === true;+ if (docRequired !== code.required) {+ findings.push({+ ...base,+ kind: 'required_mismatch',+ 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.`,+ });+ }+ }+ }+ /** @type {string[]} */+ const untraced = [];+ for (const code of read.props.values()) {+ if (+ documented.has(code.name) ||+ code.skipTagged ||+ PROPS_NOT_DOCUMENTED.includes(code.name)+ ) {+ continue;+ }+ if (!code.own) {+ if (code.untraced) untraced.push(code.name);+ continue;+ }+ findings.push({+ component: table.name,+ prop: code.name,+ kind: 'not_in_doc',+ severity: 'warning',+ message: `${table.name} declares "${code.name}", but the doc does not list it.`,+ doc: table.doc,+ source,+ });+ }+ if (untraced.length > 0) {+ propsNotChecked.push({+ component: table.name,+ doc: table.doc,+ reason: `a mapped type builds them from keys the check can't trace to the package's source, so it did not check that the doc lists them`,+ props: untraced.sort(),+ });+ }+ }++ // Field by field: collation ignores a separator such as NUL, which would+ // sort one component's findings among another's that shares its prefix.+ findings.sort(+ (a, b) =>+ a.component.localeCompare(b.component) ||+ a.prop.localeCompare(b.prop) ||+ a.kind.localeCompare(b.kind),+ );+ unchecked.sort((a, b) => a.component.localeCompare(b.component));+ return {+ status: 'checked',+ typescript: version,+ components: compared,+ findings,+ unchecked,+ ...(propsNotChecked.length > 0 ? {propsNotChecked} : {}),+ };+}diff --git a/packages/cli/foundation/discovery/prop-drift.test.mjs b/packages/cli/foundation/discovery/prop-drift.test.mjsnew file mode 100644index 0000000000..3784d6eecf--- /dev/null+++ b/packages/cli/foundation/discovery/prop-drift.test.mjs@@ -0,0 +1,554 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Documented props against a component's TypeScript props: each kind+ * of finding, and each component it cannot read.+ */++import * as fs from 'node:fs';+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';++const require = createRequire(import.meta.url);+const TYPESCRIPT_DIR = path.dirname(require.resolve('typescript/package.json'));++/** @type {string} */+let pkg;++beforeEach(() => {+ pkg = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-prop-drift-'));+ fs.writeFileSync(+ path.join(pkg, 'package.json'),+ JSON.stringify({name: '@acme/widgets', version: '1.0.0'}),+ );+ fs.writeFileSync(+ path.join(pkg, 'tsconfig.json'),+ JSON.stringify({+ compilerOptions: {+ strict: true,+ jsx: 'react-jsx',+ module: 'esnext',+ moduleResolution: 'bundler',+ target: 'es2022',+ },+ }),+ );+});++afterEach(() => {+ fs.rmSync(pkg, {recursive: true, force: true});+});++function withTypeScript() {+ fs.mkdirSync(path.join(pkg, 'node_modules'), {recursive: true});+ fs.symlinkSync(+ TYPESCRIPT_DIR,+ path.join(pkg, 'node_modules', 'typescript'),+ 'dir',+ );+}++/**+ * Write `components/<name>.tsx` and its doc; returns its prop table, which+ * also carries the component record (name, docPath, sourcePath).+ * @param {string} name+ * @param {string} source+ * @param {Record<string, any>} doc+ */+function component(name, source, doc) {+ const dir = path.join(pkg, 'components');+ fs.mkdirSync(dir, {recursive: true});+ const sourcePath = path.join(dir, `${name}.tsx`);+ const docPath = path.join(dir, `${name}.doc.mjs`);+ fs.writeFileSync(sourcePath, source);+ fs.writeFileSync(+ docPath,+ `export default ${JSON.stringify({+ type: 'component',+ name,+ displayName: name,+ description: 'Fixture.',+ ...doc,+ })};\n`,+ );+ return {+ name,+ docPath,+ sourcePath,+ doc: `components/${name}.doc.mjs`,+ props: doc.props ?? [],+ sources: [sourcePath],+ };+}++/**+ * @param {string} name+ * @param {string} type+ * @param {Record<string, unknown>} [extra]+ */+const prop = (name, type, extra = {}) => ({+ name,+ type,+ description: 'Fixture prop.',+ ...extra,+});++/** @param {import('./prop-drift.mjs').PropDriftTable[]} tables */+function compare(tables) {+ return comparePropTables(tables, {packageDir: pkg, resolveFrom: [pkg]});+}++/** @param {{findings: Array<{component: string, prop: string, kind: string}>}} report */+const kinds = report =>+ report.findings.map(f => `${f.component}.${f.prop} ${f.kind}`);++describe('comparePropTables', () => {+ it("reports a prop missing from the code, one missing from the doc, and a wrong required flag, each component's together", async () => {+ withTypeScript();+ const badge = component(+ 'Badge',+ `export type Tone = 'neutral' | 'info' | 'danger';+export interface BadgeProps {+ label: string;+ tone?: Tone;+ count?: number;+}+export function Badge(props: BadgeProps) { return null; }`,+ {+ props: [+ prop('label', 'string'),+ prop('tone', "'neutral' | 'info'"),+ prop('size', "'sm' | 'md'"),+ ],+ },+ );+ // A name that starts with another's sorts after all of the other's.+ const count = component(+ 'BadgeCount',+ 'export function BadgeCount(props: {amount?: number}) { return null; }',+ {props: []},+ );++ const report = await compare([count, badge]);++ expect(report.status).toBe('checked');+ expect(report.typescript).toMatch(/^\d+\.\d+/);+ expect(report.components).toBe(2);+ expect(kinds(report)).toEqual([+ 'Badge.count not_in_doc',+ 'Badge.label required_mismatch',+ 'Badge.size not_in_code',+ 'BadgeCount.amount not_in_doc',+ ]);+ expect(report.findings.every(f => f.severity === 'warning')).toBe(true);+ expect(+ report.findings.find(f => f.kind === 'required_mismatch'),+ ).toMatchObject({+ doc: 'components/Badge.doc.mjs',+ source: 'components/Badge.tsx',+ });+ });++ it('reads every overload, one without props included, reads a prop only some members of a union require as optional, and holds every prop one entry names to its `required`', async () => {+ withTypeScript();+ const picker = component(+ 'Picker',+ `type Single = {isMulti?: false; value: string; onChange: (value: string) => void};+type Multi = {isMulti: true; value: string[]; onChange: (value: string[]) => void};+export type PickerProps = (Single | Multi) & {label: string};+export function Picker(props: PickerProps) { return null; }`,+ {+ props: [+ prop('label', 'string', {required: true}),+ prop('isMulti', 'boolean'),+ prop('value', 'string', {required: true}),+ prop('onChange', '(value: string) => void', {required: true}),+ ],+ },+ );++ const select = component(+ 'Select',+ `type Single = {multiple?: false; value?: string};+type Multi = {multiple: true; value?: string[]; max?: number};+export function Select(props: Single): null;+export function Select(props: Multi): null;+export function Select(props: Single | Multi) { return null; }`,+ {+ props: [+ prop('multiple', 'boolean'),+ prop('value', 'string | string[]'),+ prop('max', 'number'),+ ],+ },+ );+ // An overload that takes no props makes every prop optional; a typed+ // props type beside a `Record<string, any>` or a mapped `any` index is+ // compared as it is beside an inline `[key: string]: any`.+ const propless = component(+ 'Propless',+ 'export function Propless(): null;\nexport function Propless(props: {label: string}): null;\nexport function Propless(props?: {label: string}) { return null; }',+ {props: [prop('label', 'string', {required: true})]},+ );+ const open = [+ 'Record<string, any>',+ 'Record<`data-${string}`, any>',+ '{[K in string]?: any}',+ ].map((index, i) =>+ component(+ `Open${i}`,+ `export function Open${i}(props: {label?: string; size?: number} & ${index}) { return null; }`,+ {props: [prop('label', 'string')]},+ ),+ );++ // Required in one variant only: a caller may leave it out, so optional.+ const menu = component(+ 'Menu',+ 'export function Menu(props: {items: string[]} | {alt: string}) { return null; }',+ {props: [prop('items', 'X[]', {required: true}), prop('alt', 'X')]},+ );+ // One entry's `required` is a claim about every prop it names.+ const pairs = ['label: string', 'label?: string'].map((label, i) =>+ component(+ `Pair${i}`,+ `export function Pair${i}(props: {value: string; ${label}}) { return null; }`,+ {props: [prop('value / label', 'string / string', {required: true})]},+ ),+ );+ // Typed `any` through the package's own alias of `Omit`, written in the+ // signature, as a named alias, or as an interface's base.+ const without = ['Without<any>', 'P', 'Q', 'R'].map((props, i) =>+ component(+ `Without${i}`,+ `type Without<T> = Omit<T, 'as'>; type P = Without<any>; interface Q extends Omit<any, 'as'> {} type R = Omit<P, 'ref'>;\nexport function Without${i}(props: ${props}) { return null; }`,+ {props: [prop('label', 'string')]},+ ),+ );++ const tables = [+ picker,+ select,+ propless,+ ...open,+ menu,+ ...pairs,+ ...without,+ ];+ const report = await compare(tables);++ expect(kinds(report)).toEqual([+ 'Menu.items required_mismatch',+ 'Open0.size not_in_doc',+ 'Open1.size not_in_doc',+ 'Open2.size not_in_doc',+ 'Pair1.label required_mismatch',+ 'Propless.label required_mismatch',+ ]);+ expect(report.components).toBe(9);+ expect(report.propsNotChecked).toBeUndefined();+ expect(report.unchecked.map(entry => entry.reason)).toEqual(+ [0, 1, 2, 3].map(i =>+ expect.stringMatching(`^Without${i}'s props are typed`),+ ),+ );+ });++ it('lists each component whose props it cannot read as not compared', async () => {+ withTypeScript();+ const tsconfig = path.join(pkg, 'tsconfig.json');+ const config = JSON.parse(fs.readFileSync(tsconfig, 'utf8'));+ config.compilerOptions.allowJs = true;+ fs.writeFileSync(tsconfig, JSON.stringify(config));+ /** @param {Record<string, string>} sources each component's props types */+ const missing = sources =>+ Object.entries(sources).map(([name, types]) =>+ component(+ name,+ `import type {MissingProps} from '@acme/not-installed';\n${types}\nexport function ${name}(props: ${name}Props) { return null; }`,+ {props: [prop('label', 'string')]},+ ),+ );+ const unread = [+ ...missing({+ Ghost:+ 'export interface GhostProps extends MissingProps { label?: string }',+ Omitted:+ "export interface OmittedProps extends Omit<MissingProps, 'title'> { label?: string }",+ Phantom:+ 'export type PhantomProps = Partial<MissingProps> & {label?: string};',+ Named:+ "type Base = Omit<MissingProps, 'title'>; export interface NamedProps extends Base { label?: string }",+ Joined:+ "type Base = Omit<MissingProps, 'title'>; export type JoinedProps = Base & {label?: string};",+ Bare: "type Base = Omit<MissingProps, 'title'>; export type BareProps = Base;",+ Mapped:+ 'export type MappedProps = {[K in keyof MissingProps]?: string};',+ Prefixed:+ 'type On<K extends string> = {[P in `on${K}`]?: () => void}; export type PrefixedProps = On<MissingProps> & {label?: string};',+ Picked:+ "type Base = Pick<MissingProps, 'title'>; export type PickedProps = Base;",+ Kept: "type W<T> = T & {label?: string}; export type KeptProps = W<Required<Pick<MissingProps, 'title'>>>;",+ Nested:+ "export type NestedProps = Partial<Omit<MissingProps, 'title'>> & {label?: string};",+ Deep: 'interface L1 extends MissingProps {} interface L2 extends L1 {} interface L3 extends L2 {} interface L4 extends L3 {} interface L5 extends L4 {} export interface DeepProps extends L5 { label?: string }',+ }),+ component(+ 'Wrapped',+ `import {forwardRef} from 'react';+export const Wrapped = forwardRef<HTMLButtonElement, {label?: string}>((props, ref) => null);`,+ {props: [prop('label', 'string')]},+ ),+ component(+ 'Classy',+ "import {MissingBase} from '@acme/not-installed';\nexport class Classy extends MissingBase<{label?: string}> {}\n",+ {props: [prop('label', 'string')]},+ ),+ ];+ // Each of these is the only reference in its files that does not resolve:+ // a name its module does not export, a dependency's own missing import, a+ // missing type package, and a side-effect import.+ fs.writeFileSync(+ path.join(pkg, 'components', 'theme.ts'),+ 'export interface Theme { tone?: string }\n',+ );+ const dep = path.join(pkg, 'node_modules', '@acme', 'dep');+ fs.mkdirSync(dep, {recursive: true});+ fs.writeFileSync(+ path.join(dep, 'package.json'),+ JSON.stringify({name: '@acme/dep', types: 'index.d.ts'}),+ );+ fs.writeFileSync(+ path.join(dep, 'index.d.ts'),+ "import type {MissingProps} from '@acme/not-installed';\nexport type DepProps = MissingProps & {label?: string};\n",+ );+ const references = Object.entries({+ Unnamed:+ "import type {Gone} from './theme';\nexport function Unnamed(props: {label?: string; tone?: Gone}) { return null; }\n",+ Peered:+ "import type {DepProps} from '@acme/dep';\nexport function Peered(props: DepProps) { return null; }\n",+ Referenced:+ '/// <reference types="@acme/not-installed-types" />\nexport function Referenced(props: {label?: string}) { return null; }\n',+ Effect:+ "import '@acme/not-installed-effect';\nexport function Effect(props: {label?: string}) { return null; }\n",+ // A type name declared nowhere, which only `keyof`, a `Record`'s keys+ // or a template literal key reaches.+ Omitting:+ 'export function Omitting(props: Omit<{label: string; size?: number}, keyof NowhereProps>) { return null; }\n',+ Recorded:+ 'export function Recorded(props: Partial<Record<keyof NowhereProps, string>>) { return null; }\n',+ Handlers:+ 'export function Handlers(props: {[K in `on${NowhereKey}`]?: () => void}) { return null; }\n',+ Aliased:+ 'type Keys = keyof NowhereProps;\nexport function Aliased(props: {[K in Keys]?: string}) { return null; }\n',+ // A value declared nowhere behind a binding, and a property that+ // doesn't exist: the compiler can only give either its error type.+ Valued:+ 'const d = missingValue;\nexport function Valued(props: Omit<{label: string; size?: number}, keyof typeof d>) { return null; }\n',+ Sized:+ "interface Theme { colors: {a: string} }\nexport function Sized(props: Partial<Record<keyof Theme['sizes'], string>>) { return null; }\n",+ // A value the compiler can't type, spread into an object, makes the+ // object `any`.+ Spread:+ 'interface Theme { colors: {a: string} }\ndeclare const theme: Theme;\nconst defaults = {...theme.sizes};\nexport function Spread(props: Omit<{label: string; size?: number}, keyof typeof defaults>) { return null; }\n',+ Toned:+ 'const tones = {...undeclaredTones};\nexport function Toned(props: Partial<Record<keyof typeof tones, string>>) { return null; }\n',+ }).map(([name, source]) =>+ component(name, source, {props: [prop('label', 'string')]}),+ );+ // A name declared nowhere in a JavaScript component's JSDoc, which `tsc`+ // doesn't report there.+ const documented = component(+ 'Documented',+ '/** @param {Omit<{label: string; size?: number}, keyof NowhereJs>} props */\nexport function Documented(props) { return null; }\n',+ {props: [prop('label', 'string')]},+ );+ const jsx = documented.sourcePath.replace(/\.tsx$/, '.jsx');+ fs.renameSync(documented.sourcePath, jsx);+ references.push({...documented, sourcePath: jsx, sources: [jsx]});+ // A module found without types resolves: its names are `any`.+ const untypedDir = path.join(pkg, 'node_modules', 'untyped-dep');+ fs.mkdirSync(untypedDir, {recursive: true});+ fs.writeFileSync(+ path.join(untypedDir, 'package.json'),+ JSON.stringify({name: 'untyped-dep', main: 'index.js'}),+ );+ fs.writeFileSync(+ path.join(untypedDir, 'index.js'),+ 'export const fmt = text => text;\n',+ );+ const untyped = component(+ 'Untyped',+ "import {fmt} from 'untyped-dep';\nexport function Untyped(props: {label?: string}) { fmt(props.label); return null; }\n",+ {props: [prop('label', 'string')]},+ );+ const lonely = component(+ 'Lonely',+ 'export function Other(props: {label: string}) { return null; }\n',+ {props: [prop('label', 'string', {required: true})]},+ );+ // An `any` index signature the package declares itself is no reason.+ const open = component(+ 'Open',+ 'export function Open(props: {label?: string; [key: string]: any}) { return null; }\n',+ {props: [prop('label', 'string')]},+ );+ // A missing import in the files a component comes from lists it, however+ // the props reach it: only a member's type, a value's property, a+ // conditional, `??`, a comma, or an own HOC that maps over `keyof P`.+ const reached = Object.entries({+ Member:+ 'interface Holder<T> { label?: T } export function Member(props: Holder<MissingProps>) { return null; }',+ Header:+ 'function Inner(props: {label?: string}) { return null; } const Card = Object.assign(Inner, {Header: Inner}); export const Header = Card.Header;',+ Chosen:+ 'function Inner(props: {label?: string}) { return null; } export const Chosen = (globalThis as {x?: 1}).x ? Inner : Inner;',+ Fallback:+ 'function Inner(props: {label?: string}) { return null; } export const Fallback = (undefined as typeof Inner | undefined) ?? Inner;',+ Comma:+ 'function Inner(props: {label?: string}) { return null; } export const Comma = (0, Inner);',+ Keyed:+ 'function withKeys<P>(c: (props: P) => null) { return (props: {[K in keyof P]?: string}) => c(props as P); } export const Keyed = withKeys((props: MissingProps) => null);',+ }).map(([name, source]) =>+ component(+ name,+ `import type {MissingProps} from '@acme/not-installed';\n${source}\n`,+ {props: [prop('label', 'string')]},+ ),+ );++ // Props that take names from a type parameter, such as the element a+ // component renders, accept any name until it is used.+ const PROPS_OF = [+ 'interface Intrinsic { div: {title?: string}; span: {lang?: string} }',+ 'type ElementType = keyof Intrinsic | ((props: any) => unknown);',+ 'type PropsOf<E> = E extends (props: infer P) => unknown ? P : E extends keyof Intrinsic ? Intrinsic[E] : {};',+ "type Prefixed<N extends string> = {[K in 'value' | 'change' as `${N}${Capitalize<K>}`]: string};",+ "type Pair<N extends string> = {label: string} & {[K in 'a' | 'b' as `${N}${K}`]: string};",+ 'type Relayed<M extends string> = Prefixed<M>;',+ 'type Except<O, X extends keyof O> = {[K in keyof O as K extends X ? never : K]: O[K]};',+ 'type PickByValue<O, V> = {[K in keyof O as O[K] extends V ? K : never]: O[K]};',+ ];+ const generics = Object.entries({+ Poly: "export type PolyProps<E extends ElementType> = {as?: E; padding?: number} & Omit<PropsOf<E>, 'as' | 'padding'>; export function Poly<E extends ElementType = 'div'>(props: PolyProps<E>) { return null; }",+ Joint:+ "export function Joint<E extends ElementType = 'div'>(props: {as?: E} & PropsOf<E>) { return null; }",+ Partly:+ "export function Partly<E extends ElementType = 'div'>(props: Partial<PropsOf<E>>) { return null; }",+ Remapped:+ 'export function Remapped<T extends Record<string, unknown> = {value: string}>(props: {[K in keyof T & string as `on${Capitalize<K>}Change`]?: (value: T[K]) => void}) { return null; }',+ Inferred:+ 'interface InferredBase { label?: string } export function Inferred<P extends InferredBase>(props: P) { return null; }',+ // An `as` clause that names props from one: through an alias (in an+ // intersection, or through another alias), inline, or behind a+ // condition; and keys made from one.+ PrefixAlias:+ 'export function PrefixAlias<N extends string>(props: Prefixed<N>) { return null; }',+ PrefixNested:+ 'export function PrefixNested<N extends string>(props: Pair<N>) { return null; }',+ PrefixDeep:+ 'export function PrefixDeep<N extends string>(props: Relayed<N>) { return null; }',+ Templated:+ 'export function Templated<K extends string>(props: {[P in `on${K}`]?: () => void}) { return null; }',+ PrefixInline:+ "export function PrefixInline<N extends string>(props: {[K in 'value' | 'change' as `${N}${Capitalize<K>}`]?: string}) { return null; }",+ PrefixGated:+ "export function PrefixGated<T extends boolean>(props: {[K in 'value' | 'change' as T extends true ? K : never]?: string}) { return null; }",+ // Props made from one that show the compiler no members at all.+ Bagged:+ 'interface Bag<T> {} export function Bagged<T>(props: Bag<T>) { return null; }',+ }).map(([name, source]) =>+ component(name, [...PROPS_OF, source].join('\n'), {+ props: [prop('elevation', 'number')],+ }),+ );+ // A generic whose own props take any name, or map keys of its own (an+ // `as` clause over its own key, or an alias or key filter given fixed+ // arguments), has names of its own: compared.+ const own = (/** @type {string} */ names) =>+ names.split(' ').map(name => prop(name, 'X', {required: true}));+ const owned = [+ ['GenericOpen', '{items: T[]; [key: string]: any}', 'items'],+ ['GenericRecord', '{items: T[]} & Record<string, any>', 'items'],+ ['GenericRecordKeys', "Record<'value' | 'initial', T>", 'initial value'],+ ['GenericFiltered', "{[K in 'a' | 'b' as Exclude<K, 'b'>]: T}", 'a'],+ ['GenericPrefixed', "Prefixed<'my'>", 'myChange myValue'],+ ['GenericPair', "Pair<'my'>", 'label mya myb'],+ ['GenericRelayed', "Relayed<'my'>", 'myChange myValue'],+ [+ 'GenericExcept',+ "{items: T[]} & Except<{a: string; b: string}, 'b'>",+ 'a items',+ ],+ [+ 'GenericByValue',+ '{items: T[]} & PickByValue<{onPick: () => void; size: number}, Function>',+ 'items onPick',+ ],+ ].map(([name, props, names]) =>+ component(+ name,+ [+ ...PROPS_OF,+ `export function ${name}<T>(props: ${props}) { return null; }`,+ ].join('\n'),+ {props: own(names)},+ ),+ );+ // Props that are plainly empty, generic or not, are compared: TypeScript+ // takes none of the documented props.+ const empty = ['NoProps', 'NoPropsT<T>'].map(name =>+ component(+ name.replace('<T>', ''),+ `export function ${name}(props: {}) { return null; }\n`,+ {props: [prop('label', 'string')]},+ ),+ );++ const report = await compare([+ ...unread,+ lonely,+ open,+ ...reached,+ ...references,+ untyped,+ ...generics,+ ...owned,+ ...empty,+ ]);++ expect(kinds(report)).toEqual([+ 'NoProps.label not_in_code',+ 'NoPropsT.label not_in_code',+ ]);+ expect(report.components).toBe(13);+ const generic_ =+ 'Bagged Inferred Joint Partly Poly PrefixAlias PrefixDeep PrefixGated PrefixInline PrefixNested Remapped Templated'.split(+ ' ',+ );+ expect(report.unchecked.map(u => u.component)).toEqual(+ 'Aliased Bagged Bare Chosen Classy Comma Deep Documented Effect Fallback Ghost Handlers Header Inferred Joined Joint Kept Keyed Lonely Mapped Member Named Nested Omitted Omitting Partly Peered Phantom Picked Poly PrefixAlias PrefixDeep Prefixed PrefixGated PrefixInline PrefixNested Recorded Referenced Remapped Sized Spread Templated Toned Unnamed Valued Wrapped'.split(+ ' ',+ ),+ );+ // A type the compiler can't work out, though every reference resolves.+ const untyped_ =+ 'Aliased Documented Handlers Omitting Recorded Sized Spread Toned Valued'.split(+ ' ',+ );+ for (const {component: name, reason} of report.unchecked) {+ expect(reason).toContain(+ name === 'Lonely'+ ? 'Lonely.tsx has no export named Lonely'+ : generic_.includes(name)+ ? 'from a type parameter'+ : untyped_.includes(name)+ ? "a type the compiler can't work out"+ : 'could not resolve',+ );+ }+ });+});