@astryxdesign/cli 0.7.2-canary.411cbed → 0.7.2-canary.4787e3f

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1421 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Compare a documented prop table with the props the TypeScript source
5
+ * declares for the export it describes.
6
+ *
7
+ * The compiler is the project's own `typescript`. Without one it can use, the
8
+ * comparison is skipped and says why. Every finding is a warning.
9
+ *
10
+ * Each table (a doc's `props`, or a multi-component doc's entry, with the
11
+ * export it documents and the files that may hold it) is compared with that
12
+ * export's props type:
13
+ * - `not_in_code`: a documented prop the props type does not have (a
14
+ * `data-*`-style name an index signature accepts counts as present);
15
+ * - `not_in_doc`: a prop the package's own source declares, or builds with a
16
+ * mapped type from its own keys, that the table does not list. Props from
17
+ * outside the package (React, the DOM, another package's types or keys) are
18
+ * never required, and neither are `className`, `style`, `xstyle`,
19
+ * `data-testid`, `ref`, `key`, or a prop whose declaration carries an
20
+ * `internal` JSDoc tag;
21
+ * - `required_mismatch`: `required` disagrees with whether every caller must
22
+ * pass the prop (one only some members of the props type require, or that
23
+ * the package's `defaultProps` fills, is optional, as it is to JSX
24
+ * callers; an entry that names several props claims its `required` for
25
+ * each).
26
+ *
27
+ * @input Prop tables, the package root, and the directories to resolve
28
+ * `typescript` from.
29
+ * @output A PropDriftReport.
30
+ * @position Foundation discovery: it reads the package's TypeScript and
31
+ * returns a report, and prints nothing itself.
32
+ */
33
+
34
+ import * as fs from 'node:fs';
35
+ import * as path from 'node:path';
36
+ import {readPackageTsconfig} from './package-tsconfig.mjs';
37
+ import {
38
+ resolveProjectTypeScript,
39
+ unusableTypeScriptReason,
40
+ } from './project-typescript.mjs';
41
+ import {
42
+ unresolvedGlobals,
43
+ unresolvedReference,
44
+ } from './unresolved-references.mjs';
45
+
46
+ /**
47
+ * @typedef {'not_in_code' | 'not_in_doc' | 'required_mismatch'} PropDriftKind
48
+ */
49
+
50
+ /**
51
+ * @typedef {object} PropDriftFinding
52
+ * @property {string} component the documented component (export) name
53
+ * @property {string} prop
54
+ * @property {PropDriftKind} kind
55
+ * @property {'warning'} severity
56
+ * @property {string} message
57
+ * @property {string} doc the doc file, relative to the package root
58
+ * @property {string} source the source file, relative to the package root
59
+ */
60
+
61
+ /**
62
+ * @typedef {object} PropDriftUnchecked
63
+ * @property {string} component
64
+ * @property {string} doc the doc file, relative to the package root
65
+ * @property {string} reason why its props could not be read
66
+ */
67
+
68
+ /**
69
+ * @typedef {object} PropDriftReport
70
+ * @property {'checked' | 'skipped'} status `skipped` means nothing was
71
+ * compared, and `reason` says why
72
+ * @property {string} [reason]
73
+ * @property {string} [typescript] the version of the compiler that read the props
74
+ * @property {number} components how many documented prop tables were compared
75
+ * @property {PropDriftFinding[]} findings
76
+ * @property {PropDriftUnchecked[]} unchecked documented components whose props
77
+ * could not be read from the source
78
+ * @property {Array<PropDriftUnchecked & {props: string[]}>} [propsNotChecked]
79
+ * props a mapped type builds from keys the check can't trace, which a doc
80
+ * leaving out draws no warning for
81
+ */
82
+
83
+ /**
84
+ * @typedef {object} PropDriftTable
85
+ * @property {string} doc the doc file, relative to the package root
86
+ * @property {string} name the export the table documents
87
+ * @property {any[]} props the table's entries
88
+ * @property {string[]} sources the files that may hold the export, in order
89
+ */
90
+
91
+ /**
92
+ * Props a doc never needs to list: the internal and styling props the
93
+ * `ComponentPropDoc` authoring guidance says to skip, `ref`, which Core's
94
+ * docs also leave out, and `key`, which React keeps for itself.
95
+ */
96
+ export const PROPS_NOT_DOCUMENTED = Object.freeze([
97
+ 'className',
98
+ 'style',
99
+ 'xstyle',
100
+ 'data-testid',
101
+ 'ref',
102
+ 'key',
103
+ ]);
104
+
105
+ /** The guidance's internal props: a declaration tagged `@internal`. */
106
+ const SKIP_TAGS = new Set(['internal']);
107
+
108
+ /** The line both surfaces print when the compiler is missing. */
109
+ export const TYPESCRIPT_MISSING_REASON =
110
+ 'TypeScript is not installed in this project, so documented props were not compared with the code. Install typescript and run this check again.';
111
+
112
+ /** @type {WeakMap<Function, (file: string) => boolean>} */
113
+ const MINE = new WeakMap();
114
+
115
+ /**
116
+ * Whose type names the walk checks: the package's own files and any that
117
+ * aren't a dependency's. The same test for the same own-file test.
118
+ * @param {(file: string) => boolean} isOwnFile
119
+ */
120
+ function mineFor(isOwnFile) {
121
+ let mine = MINE.get(isOwnFile);
122
+ if (!mine) {
123
+ mine = (/** @type {string} */ file) =>
124
+ isOwnFile(file) || !/[\\/]node_modules[\\/]/.test(file);
125
+ MINE.set(isOwnFile, mine);
126
+ }
127
+ return mine;
128
+ }
129
+
130
+ /**
131
+ * A memoized "is this file part of the package's own source?" test.
132
+ * @param {string} root realpath of the package root
133
+ */
134
+ function ownFileTest(root) {
135
+ /** @type {Map<string, boolean>} */
136
+ const cache = new Map();
137
+ return (/** @type {string} */ file) => {
138
+ let own = cache.get(file);
139
+ if (own !== undefined) return own;
140
+ let real = file;
141
+ try {
142
+ real = fs.realpathSync(file);
143
+ } catch {
144
+ // A lib or virtual file: compare as given.
145
+ }
146
+ const rel = path.relative(root, real);
147
+ own =
148
+ rel !== '' &&
149
+ !rel.startsWith('..') &&
150
+ !path.isAbsolute(rel) &&
151
+ !rel.split(path.sep).includes('node_modules');
152
+ cache.set(file, own);
153
+ return own;
154
+ };
155
+ }
156
+
157
+ /**
158
+ * @typedef {object} CodeProp
159
+ * @property {string} name
160
+ * @property {boolean} required whether every caller must pass it: false
161
+ * when a member of the props type, an overload, or the package's
162
+ * `defaultProps` lets a caller leave it out
163
+ * @property {boolean} own declared in the package's own source, or built
164
+ * from keys it writes
165
+ * @property {boolean} [untraced] built from keys the check can't trace
166
+ * @property {boolean} skipTagged its declaration carries an internal JSDoc tag
167
+ * @property {() => any[]} types the prop's type in each member of the props type
168
+ */
169
+
170
+ /**
171
+ * Read the props of one export.
172
+ * @param {any} ts
173
+ * @param {any} program
174
+ * @param {any} checker
175
+ * @param {string} sourcePath
176
+ * @param {string} exportName
177
+ * @param {(file: string) => boolean} isOwnFile
178
+ * @param {import('./unresolved-references.mjs').UnresolvedReference | null} ambient
179
+ * what the program's other roots cannot resolve, which any component may
180
+ * use
181
+ * @returns {{ok: true, props: Map<string, CodeProp>, accepts: (name: string) => boolean} | {ok: false, reason: string}}
182
+ */
183
+ function readCodeProps(
184
+ ts,
185
+ program,
186
+ checker,
187
+ sourcePath,
188
+ exportName,
189
+ isOwnFile,
190
+ ambient,
191
+ ) {
192
+ const sourceFile = program.getSourceFile(sourcePath);
193
+ const sourceName = path.basename(sourcePath);
194
+ if (!sourceFile) {
195
+ return {ok: false, reason: `the compiler could not read ${sourceName}`};
196
+ }
197
+ const moduleSymbol = checker.getSymbolAtLocation(sourceFile);
198
+ const exports = moduleSymbol ? checker.getExportsOfModule(moduleSymbol) : [];
199
+ const stem = sourceName.replace(/\.[cm]?[jt]sx?$/, '');
200
+ let symbol =
201
+ exports.find(/** @param {any} s */ s => s.name === exportName) ??
202
+ (stem === exportName
203
+ ? exports.find(/** @param {any} s */ s => s.name === 'default')
204
+ : undefined);
205
+ if (!symbol) {
206
+ return {
207
+ ok: false,
208
+ reason: `${sourceName} has no export named ${exportName}`,
209
+ };
210
+ }
211
+ if (symbol.flags & ts.SymbolFlags.Alias) {
212
+ symbol = checker.getAliasedSymbol(symbol);
213
+ }
214
+ // An import that does not resolve, in the files the component comes from,
215
+ // can make any part of its props a guess, whatever the code looks like.
216
+ // Some TypeScript versions read such a name as a plain `any`, so this comes
217
+ // first.
218
+ const own = [sourceFile, ...(symbol.declarations ?? [])]
219
+ .map(/** @param {any} n */ n => n.getSourceFile())
220
+ .filter(/** @param {any} sf */ sf => isOwnFile(sf.fileName));
221
+ // Type names are checked in the files that aren't a dependency's. One
222
+ // test per run, so the walk reads each file once for every component.
223
+ const mine = mineFor(isOwnFile);
224
+ const found = unresolvedReference(
225
+ ts,
226
+ program,
227
+ checker,
228
+ own,
229
+ () => true,
230
+ mine,
231
+ );
232
+ // A reference that doesn't resolve names what to install; a type the
233
+ // compiler can't give in the component's own files may only show a broken
234
+ // global one.
235
+ const missing = found && found.how !== 'used' ? found : (ambient ?? found);
236
+ if (missing) {
237
+ const where =
238
+ path.relative(path.dirname(sourcePath), missing.file) || sourceName;
239
+ return {
240
+ ok: false,
241
+ reason:
242
+ missing.how === 'used'
243
+ ? `${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`
244
+ : `${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`,
245
+ };
246
+ }
247
+ const type = checker.getTypeOfSymbolAtLocation(symbol, sourceFile);
248
+ // Each member of a union (`ComponentType<P>`: a class or a function).
249
+ const signatures = (type.isUnion() ? type.types : [type]).flatMap(
250
+ /** @param {any} t */ t => [
251
+ ...t.getCallSignatures(),
252
+ ...t.getConstructSignatures(),
253
+ ],
254
+ );
255
+ if (signatures.length === 0) {
256
+ // An `any` the source does not write comes from a type that does not
257
+ // resolve, such as `forwardRef` when React's types are not installed.
258
+ const writtenAny =
259
+ symbol.valueDeclaration?.type?.kind === ts.SyntaxKind.AnyKeyword;
260
+ const unresolved =
261
+ !writtenAny &&
262
+ (type.flags & ts.TypeFlags.Any ||
263
+ hasUnresolvedPart(ts, checker, type, 0, new Set()));
264
+ return {
265
+ ok: false,
266
+ reason: unresolved
267
+ ? `${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`
268
+ : writtenAny
269
+ ? `${exportName} is typed \`any\`, so it has no props to compare`
270
+ : `${exportName} in ${sourceName} is not a component (it cannot be called with props)`,
271
+ };
272
+ }
273
+ const unresolved = {
274
+ ok: /** @type {const} */ (false),
275
+ 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`,
276
+ };
277
+ // Every overload: its props type joins the others as a member, as a
278
+ // union's members do. An overload that takes no props makes every prop
279
+ // optional.
280
+ /** @type {any[]} */
281
+ const propsTypes = [];
282
+ let propless = false;
283
+ for (const signature of signatures) {
284
+ const parameter = signature.getParameters()[0];
285
+ if (parameter) {
286
+ propsTypes.push(checker.getTypeOfSymbolAtLocation(parameter, sourceFile));
287
+ } else {
288
+ propless = true;
289
+ }
290
+ }
291
+ /** @type {Map<string, CodeProp>} */
292
+ const props = new Map();
293
+ if (propsTypes.length === 0) return {ok: true, props, accepts: () => false};
294
+
295
+ // Props that are `any`, written so or made from it (`FC<any>`, or
296
+ // `forwardRef<E, any>`'s `Omit<any, 'ref'>`).
297
+ if (propsTypes.some(propsType => isAnyProps(ts, checker, propsType))) {
298
+ return {
299
+ ok: false,
300
+ reason: `${exportName}'s props are typed \`any\`, so there is nothing to compare them with`,
301
+ };
302
+ }
303
+ if (
304
+ propsTypes.some(propsType =>
305
+ hasUnresolvedPart(ts, checker, propsType, 0, new Set()),
306
+ )
307
+ ) {
308
+ return unresolved;
309
+ }
310
+
311
+ const members = propsTypes
312
+ .flatMap(propsType => (propsType.isUnion() ? propsType.types : [propsType]))
313
+ .filter(
314
+ /** @param {any} t */
315
+ t => !(t.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Null)),
316
+ );
317
+ // A generic component whose props take their names from a type parameter
318
+ // (the element it renders: `Omit<ComponentPropsWithoutRef<E>, 'as'>`, or a
319
+ // bare `props: P`) accepts names that are known only where it is used.
320
+ const generic = signatures.some(
321
+ /** @param {any} signature */ signature =>
322
+ (signature.getTypeParameters?.() ?? []).length > 0,
323
+ );
324
+ // Props that refer to a type parameter and show the compiler no members
325
+ // at all would draw a finding for every documented name: listed too.
326
+ const unnamed =
327
+ members.some(member => isDeferred(ts, checker, member, true)) &&
328
+ members.every(
329
+ member =>
330
+ checker.getPropertiesOfType(member).length === 0 &&
331
+ (checker.getIndexInfosOfType?.(member) ?? []).length === 0,
332
+ );
333
+ if (
334
+ generic &&
335
+ (unnamed ||
336
+ members.some(member => namesFromTypeParameter(ts, checker, member, 0)))
337
+ ) {
338
+ return {
339
+ ok: false,
340
+ 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`,
341
+ };
342
+ }
343
+ // `defaultProps` the package sets (a class's static field, one assigned to a
344
+ // function, or the wrapped component's through up to two layers of `memo`
345
+ // and `lazy`, as React's JSX types read it) lets JSX callers leave its props
346
+ // out; `any` fills every prop. React's own types declare an optional one on
347
+ // every component type.
348
+ let holder = type;
349
+ for (let i = 0; i < 2 && checker.getPropertyOfType(holder, '$$typeof'); i++) {
350
+ const inner =
351
+ checker.getPropertyOfType(holder, 'type') ??
352
+ checker.getPropertyOfType(holder, '_result');
353
+ if (!inner) break;
354
+ holder = checker.getTypeOfSymbolAtLocation(inner, sourceFile);
355
+ }
356
+ const defaultProps = checker.getPropertyOfType(holder, 'defaultProps');
357
+ const defaults = defaultProps?.declarations?.some(
358
+ /** @param {any} d */ d => isOwnFile(d.getSourceFile().fileName),
359
+ )
360
+ ? checker.getTypeOfSymbolAtLocation(defaultProps, sourceFile)
361
+ : null;
362
+ const fillsAll = !!defaults && !!(defaults.flags & ts.TypeFlags.Any);
363
+ const defaulted = new Set(
364
+ defaults
365
+ ? checker
366
+ .getPropertiesOfType(defaults)
367
+ .map(/** @param {any} s */ s => s.name)
368
+ : [],
369
+ );
370
+
371
+ /** @type {Map<string, {symbols: any[], optional: number}>} */
372
+ const byName = new Map();
373
+ for (const member of members) {
374
+ for (const prop of checker.getPropertiesOfType(member)) {
375
+ const entry = byName.get(prop.name) ?? {symbols: [], optional: 0};
376
+ entry.symbols.push(prop);
377
+ if (prop.flags & ts.SymbolFlags.Optional) entry.optional++;
378
+ byName.set(prop.name, entry);
379
+ }
380
+ }
381
+ if (fillsAll) for (const name of byName.keys()) defaulted.add(name);
382
+
383
+ /** @type {((prop: any) => string) | undefined} */
384
+ let origin;
385
+ // Read from the component's declaration, its props parameter's, and the
386
+ // wrapped component's for `memo` and `lazy`.
387
+ const originOf = (/** @type {any} */ prop) =>
388
+ (origin ??= mappedPropOrigin(ts, checker, isOwnFile, [
389
+ symbol.valueDeclaration ?? symbol.declarations?.[0],
390
+ ...[
391
+ ...signatures,
392
+ ...(holder === type ? [] : holder.getCallSignatures()),
393
+ ].map(
394
+ (/** @type {any} */ signature) =>
395
+ signature.getParameters()[0]?.valueDeclaration,
396
+ ),
397
+ ]))(prop);
398
+ for (const [name, {symbols, optional}] of byName) {
399
+ const declarations = symbols.flatMap(
400
+ /** @param {any} s */ s => s.declarations ?? [],
401
+ );
402
+ const ownDeclarations = declarations.filter(
403
+ /** @param {any} d */ d => isOwnFile(d.getSourceFile().fileName),
404
+ );
405
+ // A prop no declaration names, one a mapped type builds, is the
406
+ // package's own when its key comes from the package's own source.
407
+ const built =
408
+ declarations.length === 0 ? strongest(symbols.map(originOf)) : null;
409
+ // Optional when a caller may leave it out: an overload that takes no
410
+ // props, or a member of the props type that does not require it.
411
+ const required =
412
+ !defaulted.has(name) &&
413
+ !propless &&
414
+ symbols.length === members.length &&
415
+ optional === 0;
416
+ props.set(name, {
417
+ name,
418
+ required,
419
+ own: ownDeclarations.length > 0 || built === 'own',
420
+ untraced:
421
+ declarations.length === 0 && built !== 'own' && built !== 'foreign',
422
+ skipTagged: ownDeclarations.some(
423
+ /** @param {any} d */
424
+ d =>
425
+ ts
426
+ .getJSDocTags(d)
427
+ .some(
428
+ /** @param {any} tag */ tag => SKIP_TAGS.has(tag.tagName.text),
429
+ ),
430
+ ),
431
+ types: () =>
432
+ symbols.map(
433
+ /** @param {any} s */ s =>
434
+ checker.getTypeOfSymbolAtLocation(s, sourceFile),
435
+ ),
436
+ });
437
+ }
438
+
439
+ /** Does an index signature of the props type accept this name? */
440
+ const accepts = (/** @type {string} */ name) =>
441
+ members.some(
442
+ /** @param {any} member */ member =>
443
+ (checker.getIndexInfosOfType?.(member) ?? []).some(
444
+ /** @param {any} info */ info =>
445
+ !holdsNothing(ts, info.type) &&
446
+ keyAccepts(ts, checker, info.keyType, name),
447
+ ),
448
+ );
449
+ return {ok: true, props, accepts};
450
+ }
451
+
452
+ /**
453
+ * The props one doc entry names. `a / b` documents each of `a` and `b`, with
454
+ * the entry's `required` (and the type split the same way when it splits
455
+ * into as many parts); `x.y` (or
456
+ * `x[].y`) documents a field of prop `x`; `...rest` documents a spread of
457
+ * another props type and is not compared.
458
+ * @param {any} raw
459
+ * @returns {Array<{name: string, written: string, path: string[], spread: boolean, type?: string, required?: boolean}>}
460
+ */
461
+ function documentedProps(raw) {
462
+ const names = String(raw.name)
463
+ .split(/\s+\/\s+/)
464
+ .map(name => name.trim())
465
+ .filter(Boolean);
466
+ const types = typeof raw.type === 'string' ? raw.type.split(/\s+\/\s+/) : [];
467
+ return names.map((written, i) => {
468
+ const spread = written.startsWith('...');
469
+ const [root = written, ...path] = written
470
+ .replace(/\[\]/g, '')
471
+ .split('.')
472
+ .filter(Boolean);
473
+ return {
474
+ name: spread ? written : root,
475
+ written,
476
+ path: spread ? [] : path,
477
+ spread,
478
+ type:
479
+ names.length === 1
480
+ ? raw.type
481
+ : types.length === names.length
482
+ ? types[i]
483
+ : undefined,
484
+ required: raw.required,
485
+ };
486
+ });
487
+ }
488
+
489
+ /**
490
+ * The types a field can sit on: each member of a union, through arrays and
491
+ * tuples at any depth (`grid[][].id`).
492
+ * @param {any} ts
493
+ * @param {any} checker
494
+ * @param {any} type
495
+ * @param {number} [depth]
496
+ * @returns {any[]}
497
+ */
498
+ function holders(ts, checker, type, depth = 0) {
499
+ if (depth > 8) return [type];
500
+ if (type.isUnion()) {
501
+ return type.types.flatMap(
502
+ /** @param {any} t */ t => holders(ts, checker, t, depth + 1),
503
+ );
504
+ }
505
+ const array =
506
+ ['Array', 'ReadonlyArray'].includes(type.symbol?.name) ||
507
+ type.target?.objectFlags & ts.ObjectFlags.Tuple;
508
+ if (array && type.objectFlags & ts.ObjectFlags.Reference) {
509
+ return checker
510
+ .getTypeArguments(type)
511
+ .flatMap(/** @param {any} t */ t => holders(ts, checker, t, depth + 1));
512
+ }
513
+ return [type];
514
+ }
515
+
516
+ /**
517
+ * Does a field path exist in a prop's type, in at least one member of a
518
+ * union (through arrays)?
519
+ * @param {any} ts
520
+ * @param {any} checker
521
+ * @param {CodeProp} code
522
+ * @param {string[]} fieldPath
523
+ */
524
+ function fieldExists(ts, checker, code, fieldPath) {
525
+ /** @type {any[]} */
526
+ let current = code.types();
527
+ for (const field of fieldPath) {
528
+ /** @type {any[]} */
529
+ const next = [];
530
+ for (const holder of current.flatMap(t => holders(ts, checker, t))) {
531
+ if (holder.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) return true;
532
+ const prop = checker.getPropertyOfType(holder, field);
533
+ // Or a field an index signature takes (`Record<string, string>`).
534
+ const index = prop
535
+ ? null
536
+ : (checker.getIndexInfosOfType?.(holder) ?? []).find(
537
+ /** @param {any} info */ info =>
538
+ !holdsNothing(ts, info.type) &&
539
+ keyAccepts(ts, checker, info.keyType, field),
540
+ );
541
+ if (prop) next.push(checker.getTypeOfSymbol(prop));
542
+ else if (index) next.push(index.type);
543
+ }
544
+ if (next.length === 0) return false;
545
+ current = next;
546
+ }
547
+ return true;
548
+ }
549
+
550
+ /**
551
+ * Is a type the compiler's stand-in for a name it could not resolve?
552
+ * @param {any} ts
553
+ * @param {any} type
554
+ */
555
+ function isErrorType(ts, type) {
556
+ return (
557
+ (type.flags & ts.TypeFlags.Any) !== 0 && type.intrinsicName === 'error'
558
+ );
559
+ }
560
+
561
+ /**
562
+ * Do some of a generic component's prop names come from a type parameter:
563
+ * a deferred type, an index signature keyed or valued by a type made from
564
+ * one, or a mapped type whose keys are one (`Partial<P>`) or whose `as`
565
+ * clause uses one? An interface whose values alone use it (`ListProps<T>`),
566
+ * a mapping over keys of its own (`Record<'value', V>`), and an index that
567
+ * takes any name (`[key: string]: any`) give names of its own.
568
+ * @param {any} ts
569
+ * @param {any} checker
570
+ * @param {any} type
571
+ * @param {number} depth
572
+ * @returns {boolean}
573
+ */
574
+ function namesFromTypeParameter(ts, checker, type, depth) {
575
+ if (depth > 8) return false;
576
+ if (type.isUnion() || type.isIntersection()) {
577
+ return type.types.some(
578
+ /** @param {any} t */ t =>
579
+ namesFromTypeParameter(ts, checker, t, depth + 1),
580
+ );
581
+ }
582
+ if (isDeferred(ts, checker, type)) return true;
583
+ if (
584
+ (checker.getIndexInfosOfType?.(type) ?? []).some(
585
+ /** @param {any} info */ info =>
586
+ isDeferred(ts, checker, info.type, true) ||
587
+ isDeferred(ts, checker, info.keyType, true),
588
+ )
589
+ ) {
590
+ return true;
591
+ }
592
+ if ((type.objectFlags & ts.ObjectFlags.Mapped) === 0) return false;
593
+ // The keys, which the compiler works out when it reads the members.
594
+ checker.getPropertiesOfType(type);
595
+ return (
596
+ (!!type.constraintType && isDeferred(ts, checker, type.constraintType)) ||
597
+ renamedByTypeParameter(ts, checker, type)
598
+ );
599
+ }
600
+
601
+ /**
602
+ * Does a mapping's `as` clause use a type parameter besides its own key that
603
+ * is still open where the props are read: one the component declares, or one
604
+ * an alias passes on whose argument is still a type parameter (`` as
605
+ * `${N}${K}` ``, `as T extends true ? K : never`)? Given fixed arguments
606
+ * (`Prefixed<'my'>`, a key filter such as `Except<Props, 'b'>`), every key
607
+ * gets its name. Its own key, and an `infer` inside the clause, are known
608
+ * for each key.
609
+ * @param {any} ts
610
+ * @param {any} checker
611
+ * @param {any} type a mapped type
612
+ * @returns {boolean}
613
+ */
614
+ function renamedByTypeParameter(ts, checker, type) {
615
+ const clause = type.declaration?.nameType;
616
+ if (!clause) return false;
617
+ /** @type {(node: any) => boolean} */
618
+ const uses = node => {
619
+ const symbol = ts.isTypeReferenceNode(node)
620
+ ? checker.getSymbolAtLocation(node.typeName)
621
+ : undefined;
622
+ const declaration =
623
+ symbol && symbol.flags & ts.SymbolFlags.TypeParameter
624
+ ? symbol.declarations?.[0]
625
+ : undefined;
626
+ const inClause =
627
+ declaration?.getSourceFile() === clause.getSourceFile() &&
628
+ declaration.pos >= clause.pos &&
629
+ declaration.end <= clause.end;
630
+ if (
631
+ declaration &&
632
+ declaration !== type.declaration.typeParameter &&
633
+ !inClause
634
+ ) {
635
+ // Its value where the props are read, through the instantiation.
636
+ const value = valueIn(
637
+ ts,
638
+ checker,
639
+ checker.getDeclaredTypeOfSymbol(symbol),
640
+ type.mapper,
641
+ 0,
642
+ );
643
+ if (!value || isDeferred(ts, checker, value, true)) return true;
644
+ }
645
+ return !!ts.forEachChild(
646
+ node,
647
+ /** @param {any} child */ child => uses(child) || undefined,
648
+ );
649
+ };
650
+ return uses(clause);
651
+ }
652
+
653
+ /**
654
+ * The value an instantiation gives a type parameter, as the compiler's own
655
+ * mappers give it, through each mapper one combines; null when that takes
656
+ * more than following parameters (a value made from one, or a mapper of
657
+ * another form), which counts as open.
658
+ * @param {any} ts
659
+ * @param {any} checker
660
+ * @param {any} parameter
661
+ * @param {any} mapper
662
+ * @param {number} depth
663
+ * @returns {any}
664
+ */
665
+ function valueIn(ts, checker, parameter, mapper, depth) {
666
+ if (!mapper) return parameter;
667
+ if (depth > 32) return null;
668
+ if (mapper.mapper1 && mapper.mapper2) {
669
+ const first = valueIn(ts, checker, parameter, mapper.mapper1, depth + 1);
670
+ if (!first) return null;
671
+ if (first === parameter || first.flags & ts.TypeFlags.TypeParameter) {
672
+ return valueIn(ts, checker, first, mapper.mapper2, depth + 1);
673
+ }
674
+ return isDeferred(ts, checker, first, true) ? null : first;
675
+ }
676
+ if ('source' in mapper) {
677
+ return mapper.source === parameter ? mapper.target : parameter;
678
+ }
679
+ if (Array.isArray(mapper.sources)) {
680
+ const i = mapper.sources.indexOf(parameter);
681
+ if (i < 0) return parameter;
682
+ const target = mapper.targets?.[i];
683
+ return typeof target === 'function' ? target() : (target ?? null);
684
+ }
685
+ return typeof mapper.func === 'function' ? mapper.func(parameter) : null;
686
+ }
687
+
688
+ /**
689
+ * A type parameter, or a type the compiler defers until one is known (an
690
+ * indexed access, a conditional), or a union, intersection or template
691
+ * literal with one (`on${K}`, `Capitalize<K>`); with `deep`, also a type made
692
+ * from one (through alias or reference arguments).
693
+ * @param {any} ts
694
+ * @param {any} checker
695
+ * @param {any} t
696
+ * @param {boolean} [deep]
697
+ * @param {number} [depth]
698
+ * @returns {boolean}
699
+ */
700
+ function isDeferred(ts, checker, t, deep = false, depth = 0) {
701
+ const F = ts.TypeFlags;
702
+ if (
703
+ t.flags &
704
+ (F.TypeParameter |
705
+ F.IndexedAccess |
706
+ F.Conditional |
707
+ F.Substitution |
708
+ F.Index)
709
+ ) {
710
+ return true;
711
+ }
712
+ if (depth > 6) return false;
713
+ const parts = [
714
+ ...(t.isUnion() || t.isIntersection() ? t.types : []),
715
+ ...(t.flags & F.TemplateLiteral ? (t.types ?? []) : []),
716
+ ...(t.flags & F.StringMapping && t.type ? [t.type] : []),
717
+ ...(deep ? (t.aliasTypeArguments ?? []) : []),
718
+ ...(deep && t.objectFlags & ts.ObjectFlags.Reference
719
+ ? checker.getTypeArguments(t)
720
+ : []),
721
+ ];
722
+ return parts.some(u => isDeferred(ts, checker, u, deep, depth + 1));
723
+ }
724
+
725
+ /**
726
+ * Does an index signature's key take this prop name, as TypeScript would? A
727
+ * `string` key takes any name; a template literal key only the names that
728
+ * match it (`data-${string}`, `col${number}`, `on${Capitalize<string>}`).
729
+ * @param {any} ts
730
+ * @param {any} checker
731
+ * @param {any} key
732
+ * @param {string} name
733
+ */
734
+ function keyAccepts(ts, checker, key, name) {
735
+ if (key.flags & ts.TypeFlags.String) return true;
736
+ if (!(key.flags & ts.TypeFlags.TemplateLiteral)) return false;
737
+ if (checker.getStringLiteralType && checker.isTypeAssignableTo) {
738
+ return checker.isTypeAssignableTo(checker.getStringLiteralType(name), key);
739
+ }
740
+ // An older TypeScript has no literal-type factory: match the template.
741
+ /** @type {Record<string, string>} */
742
+ const mappings = {
743
+ Uppercase: '[^a-z]*',
744
+ Lowercase: '[^A-Z]*',
745
+ Capitalize: '(?:[^a-z][\\s\\S]*)?',
746
+ Uncapitalize: '(?:[^A-Z][\\s\\S]*)?',
747
+ };
748
+ const spans = (key.types ?? []).map(
749
+ /** @param {any} span */ span =>
750
+ span.flags & ts.TypeFlags.Number
751
+ ? '[-+]?(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][-+]?\\d+)?'
752
+ : (mappings[String(span.symbol?.escapedName)] ?? '[\\s\\S]*'),
753
+ );
754
+ const pattern = (key.texts ?? [])
755
+ .map(
756
+ (/** @type {string} */ text, /** @type {number} */ i) =>
757
+ text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + (spans[i] ?? ''),
758
+ )
759
+ .join('');
760
+ return new RegExp(`^${pattern}$`).test(name);
761
+ }
762
+
763
+ /**
764
+ * Can a value of this type be passed at all? `never`, or only `undefined`
765
+ * (`Record<string, never>`, the usual way to write "no props"), cannot.
766
+ * @param {any} ts
767
+ * @param {any} type
768
+ */
769
+ function holdsNothing(ts, type) {
770
+ const parts = type.isUnion() ? type.types : [type];
771
+ return parts.every(
772
+ /** @param {any} t */ t =>
773
+ t.flags & (ts.TypeFlags.Never | ts.TypeFlags.Undefined),
774
+ );
775
+ }
776
+
777
+ /** @param {Array<string | null>} found the answers for one key, by place */
778
+ const strongest = found =>
779
+ ['own', 'foreign', 'unknown'].find(answer => found.includes(answer)) ?? null;
780
+
781
+ /**
782
+ * Where the key of a prop a mapped type builds, which no declaration names,
783
+ * comes from: `own` when the package's own source writes it, as a literal or
784
+ * a property's declaration, `foreign` when another package's types do, and
785
+ * `unknown` when the check can't trace it. It reads the mapping where the
786
+ * component's declaration and props parameter reach it (and the component a
787
+ * `memo`, `lazy` or `forwardRef` call wraps), through aliases, a generic's
788
+ * arguments, `keyof`, `typeof`, and a conditional's branches (`Exclude`,
789
+ * `Extract`).
790
+ * @param {any} ts
791
+ * @param {any} checker
792
+ * @param {(file: string) => boolean} isOwnFile
793
+ * @param {any[]} starts
794
+ * @returns {(prop: any) => string}
795
+ */
796
+ function mappedPropOrigin(ts, checker, isOwnFile, starts) {
797
+ /** @type {Map<any, Map<any, any>[]>} each mapping, with its type arguments */
798
+ const sites = new Map();
799
+ let budget = 5000;
800
+ /** @param {any} node */
801
+ const where = node =>
802
+ isOwnFile(node.getSourceFile().fileName) ? 'own' : 'foreign';
803
+ /** @param {any} node */
804
+ const target = node => {
805
+ let symbol = checker.getSymbolAtLocation(
806
+ node.typeName ?? node.exprName ?? node.expression ?? node,
807
+ );
808
+ if (symbol && symbol.flags & ts.SymbolFlags.Alias) {
809
+ symbol = checker.getAliasedSymbol(symbol);
810
+ }
811
+ return symbol;
812
+ };
813
+ /** @type {(params: any, args: any, env: Map<any, any>) => Map<any, any>} */
814
+ const bind = (params, args, env) => {
815
+ const next = new Map(env);
816
+ (params ?? []).forEach(
817
+ (/** @type {any} */ param, /** @type {number} */ i) => {
818
+ const node = args?.[i] ?? param.default;
819
+ if (node)
820
+ next.set(target(param.name), {node, env: args?.[i] ? env : next});
821
+ },
822
+ );
823
+ return next;
824
+ };
825
+ /** @type {(node: any, env: Map<any, any>, depth: number) => void} */
826
+ const visit = (node, env, depth) => {
827
+ if (!node || depth > 40 || budget-- <= 0) return;
828
+ if (ts.isMappedTypeNode(node)) {
829
+ sites.set(node, [...(sites.get(node) ?? []), env]);
830
+ }
831
+ const reference =
832
+ ts.isTypeReferenceNode(node) || ts.isExpressionWithTypeArguments(node);
833
+ // A component another binding wraps: `memo(Inner)`, `forwardRef(Impl)`.
834
+ const wrapped =
835
+ ts.isIdentifier(node) &&
836
+ (ts.isCallExpression(node.parent) ||
837
+ ts.isVariableDeclaration(node.parent)) &&
838
+ node !== node.parent.expression &&
839
+ node !== node.parent.name;
840
+ for (const declaration of reference || wrapped
841
+ ? (target(node)?.declarations ?? [])
842
+ : []) {
843
+ const own = where(declaration) === 'own';
844
+ if (reference && ts.isTypeAliasDeclaration(declaration)) {
845
+ visit(
846
+ declaration.type,
847
+ bind(declaration.typeParameters, node.typeArguments, env),
848
+ depth + 1,
849
+ );
850
+ } else if (reference && (own || !node.typeArguments)) {
851
+ // Another package's interface: only what it extends.
852
+ const next = bind(declaration.typeParameters, node.typeArguments, env);
853
+ if (own) visit(declaration, next, depth + 1);
854
+ else
855
+ for (const clause of declaration.heritageClauses ?? [])
856
+ visit(clause, next, depth + 1);
857
+ } else if (wrapped && own) {
858
+ visit(declaration, env, depth + 1);
859
+ }
860
+ }
861
+ ts.forEachChild(node, (/** @type {any} */ child) =>
862
+ visit(child, env, depth + 1),
863
+ );
864
+ };
865
+ /** @type {(node: any, key: string, env: Map<any, any>, depth: number) => string | null} */
866
+ const keyOrigin = (node, key, env, depth) => {
867
+ if (!node || depth > 40) return 'unknown';
868
+ const next = (/** @type {any} */ inner) =>
869
+ keyOrigin(inner, key, env, depth + 1);
870
+ if (ts.isParenthesizedTypeNode(node)) return next(node.type);
871
+ if (ts.isLiteralTypeNode(node)) {
872
+ return node.literal.text === key ? where(node) : null;
873
+ }
874
+ if (ts.isUnionTypeNode(node)) return strongest(node.types.map(next));
875
+ if (ts.isConditionalTypeNode(node)) {
876
+ return strongest([next(node.trueType), next(node.falseType)]);
877
+ }
878
+ if (
879
+ ts.isTypeOperatorNode(node) &&
880
+ node.operator === ts.SyntaxKind.KeyOfKeyword
881
+ ) {
882
+ const of =
883
+ ts.isTypeReferenceNode(node.type) && env.get(target(node.type));
884
+ const prop = checker.getPropertyOfType(
885
+ checker.getTypeFromTypeNode(of ? of.node : node.type),
886
+ key,
887
+ );
888
+ return prop ? propOrigin(prop, depth + 1) : null;
889
+ }
890
+ if (ts.isArrayTypeNode(node)) return next(node.elementType);
891
+ if (ts.isTupleTypeNode(node)) return strongest(node.elements.map(next));
892
+ if (ts.isTypeOperatorNode(node)) return next(node.type);
893
+ if (ts.isIndexedAccessTypeNode(node)) {
894
+ // `Props['size']` reads the property's own type; `(typeof SIZES)[number]`
895
+ // reads the value's.
896
+ const index = ts.isLiteralTypeNode(node.indexType)
897
+ ? node.indexType.literal.text
898
+ : undefined;
899
+ if (index === undefined) return next(node.objectType);
900
+ const declared = checker.getPropertyOfType(
901
+ checker.getTypeFromTypeNode(node.objectType),
902
+ index,
903
+ )?.declarations?.[0];
904
+ return declared ? valueOrigin(declared, key, depth + 1) : 'unknown';
905
+ }
906
+ if (ts.isTypeQueryNode(node)) {
907
+ return valueOrigin(target(node)?.valueDeclaration, key, depth + 1);
908
+ }
909
+ if (ts.isTypeReferenceNode(node)) {
910
+ const symbol = target(node);
911
+ const bound = symbol && env.get(symbol);
912
+ if (bound) return keyOrigin(bound.node, key, bound.env, depth + 1);
913
+ const alias = symbol?.declarations?.find(ts.isTypeAliasDeclaration);
914
+ if (alias) {
915
+ return keyOrigin(
916
+ alias.type,
917
+ key,
918
+ bind(alias.typeParameters, node.typeArguments, env),
919
+ depth + 1,
920
+ );
921
+ }
922
+ // An enum: where it is declared. A type parameter no argument binds,
923
+ // such as an `infer`, can't be traced.
924
+ if (
925
+ symbol &&
926
+ symbol.flags & (ts.SymbolFlags.Enum | ts.SymbolFlags.EnumMember)
927
+ ) {
928
+ return where(symbol.declarations[0]);
929
+ }
930
+ }
931
+ return 'unknown';
932
+ };
933
+ /**
934
+ * Where a value's literal keys are written: its declared type, or the
935
+ * literals its initializer writes, through `as const` and other bindings.
936
+ * @type {(node: any, key: string, depth: number) => string | null}
937
+ */
938
+ const valueOrigin = (node, key, depth) => {
939
+ if (!node || depth > 40) return 'unknown';
940
+ if (ts.isStringLiteralLike(node) || ts.isNumericLiteral(node)) {
941
+ return node.text === key ? where(node) : null;
942
+ }
943
+ if (ts.isArrayLiteralExpression(node)) {
944
+ return strongest(
945
+ node.elements.map((/** @type {any} */ e) =>
946
+ valueOrigin(e, key, depth + 1),
947
+ ),
948
+ );
949
+ }
950
+ // A declared type or a cast, but not `as const` or `satisfies`.
951
+ const written =
952
+ node.type &&
953
+ !ts.isSatisfiesExpression?.(node) &&
954
+ node.type.typeName?.text !== 'const';
955
+ if (written) return keyOrigin(node.type, key, new Map(), depth + 1);
956
+ const inner = node.initializer ?? node.expression;
957
+ if (inner) return valueOrigin(inner, key, depth + 1);
958
+ if (ts.isIdentifier(node)) {
959
+ let symbol = checker.getSymbolAtLocation(node);
960
+ if (symbol && symbol.flags & ts.SymbolFlags.Alias) {
961
+ symbol = checker.getAliasedSymbol(symbol);
962
+ }
963
+ return valueOrigin(symbol?.valueDeclaration, key, depth + 1);
964
+ }
965
+ return 'unknown';
966
+ };
967
+ /** @type {(prop: any, depth: number) => string | null} */
968
+ const propOrigin = (prop, depth) => {
969
+ if (depth > 40) return 'unknown';
970
+ const declarations = prop.declarations ?? [];
971
+ if (declarations.length > 0) {
972
+ return declarations.some((/** @type {any} */ d) => where(d) === 'own')
973
+ ? 'own'
974
+ : 'foreign';
975
+ }
976
+ const links = prop.links ?? prop;
977
+ if (links.syntheticOrigin)
978
+ return propOrigin(links.syntheticOrigin, depth + 1);
979
+ if (links.containingType) {
980
+ return strongest(
981
+ links.containingType.types.map((/** @type {any} */ t) => {
982
+ const part = checker.getPropertyOfType(t, prop.name);
983
+ return part && part !== prop ? propOrigin(part, depth + 1) : null;
984
+ }),
985
+ );
986
+ }
987
+ const mapping = links.mappedType?.declaration;
988
+ const key = links.keyType?.value;
989
+ if (!mapping || key === undefined) return 'unknown';
990
+ return strongest(
991
+ (sites.get(mapping) ?? []).map(env =>
992
+ keyOrigin(
993
+ mapping.typeParameter.constraint,
994
+ String(key),
995
+ env,
996
+ depth + 1,
997
+ ),
998
+ ),
999
+ );
1000
+ };
1001
+ for (const start of starts) {
1002
+ if (start && where(start) === 'own') visit(start, new Map(), 0);
1003
+ }
1004
+ return prop => propOrigin(prop, 0) ?? 'unknown';
1005
+ }
1006
+
1007
+ /**
1008
+ * Are props `any`: a plain `any` (not one standing for a name that does not
1009
+ * resolve), or a type an alias makes from `any` by reading its keys, which
1010
+ * takes every name (`Omit<any, 'ref'>`, or React's `Omit` of one)? `Record<string, any>` only gives
1011
+ * names an `any` value, as an inline `[key: string]: any` does.
1012
+ * @param {any} ts
1013
+ * @param {any} checker
1014
+ * @param {any} type
1015
+ * @param {number} [depth] how far into an alias's arguments
1016
+ * @returns {boolean}
1017
+ */
1018
+ function isAnyProps(ts, checker, type, depth = 0) {
1019
+ if (type.flags & ts.TypeFlags.Any) return !isErrorType(ts, type);
1020
+ const parts = type.isUnion() || type.isIntersection() ? type.types : [type];
1021
+ /** @type {(node: any) => any} the symbol a reference names */
1022
+ const target = node => {
1023
+ const used = checker.getSymbolAtLocation(node.typeName ?? node.expression);
1024
+ return used && used.flags & ts.SymbolFlags.Alias
1025
+ ? checker.getAliasedSymbol(used)
1026
+ : used;
1027
+ };
1028
+ /** @type {(node: any) => any} */
1029
+ const aliasOf = node =>
1030
+ target(node)?.declarations?.find(ts.isTypeAliasDeclaration);
1031
+ // Whether an alias reads its `i`th parameter's keys: `keyof T`, or `T`
1032
+ // passed on to an alias that does, as `type Without<T> = Omit<T, 'as'>`.
1033
+ /** @type {(alias: any, i: number, depth?: number) => boolean} */
1034
+ const readsKeys = (alias, i, depth = 0) => {
1035
+ const name = alias?.typeParameters?.[i]?.name.text;
1036
+ /** @type {(node: any) => boolean} */
1037
+ const visit = node =>
1038
+ (ts.isTypeOperatorNode(node) &&
1039
+ node.operator === ts.SyntaxKind.KeyOfKeyword &&
1040
+ node.type.typeName?.text === name) ||
1041
+ (ts.isTypeReferenceNode(node) &&
1042
+ depth < 8 &&
1043
+ (node.typeArguments ?? []).some(
1044
+ (/** @type {any} */ arg, /** @type {number} */ j) =>
1045
+ arg.typeName?.text === name &&
1046
+ readsKeys(aliasOf(node), j, depth + 1),
1047
+ )) ||
1048
+ !!ts.forEachChild(
1049
+ node,
1050
+ (/** @type {any} */ child) => visit(child) || undefined,
1051
+ );
1052
+ return !!name && visit(alias);
1053
+ };
1054
+ /** @type {(symbol: any) => any[]} an alias's type, or an interface's bases */
1055
+ const shapeOf = symbol =>
1056
+ (symbol?.declarations ?? []).flatMap((/** @type {any} */ d) =>
1057
+ ts.isTypeAliasDeclaration(d)
1058
+ ? [d.type]
1059
+ : (d.heritageClauses?.flatMap((/** @type {any} */ c) => c.types) ?? []),
1060
+ );
1061
+ // `any`, or such a type, passed where an alias reads its keys, written in
1062
+ // the props type or one of the package's names for it (`type P =
1063
+ // Without<any>`, `interface P extends Omit<Omit<any, 'as'>, 'ref'>`).
1064
+ /** @type {(node: any, depth: number) => boolean} */
1065
+ const anyKeyed = (node, depth) => {
1066
+ if (!node || depth > 8) return false;
1067
+ if (node.kind === ts.SyntaxKind.AnyKeyword) return true;
1068
+ if (ts.isParenthesizedTypeNode(node)) return anyKeyed(node.type, depth + 1);
1069
+ if (ts.isUnionTypeNode(node) || ts.isIntersectionTypeNode(node)) {
1070
+ return node.types.some((/** @type {any} */ t) => anyKeyed(t, depth + 1));
1071
+ }
1072
+ // A reference: `Name<…>`, or an interface's `extends Name<…>`.
1073
+ if (!node.typeName && !node.expression) return false;
1074
+ const alias = aliasOf(node);
1075
+ return node.typeArguments
1076
+ ? node.typeArguments.some(
1077
+ (/** @type {any} */ arg, /** @type {number} */ i) =>
1078
+ anyKeyed(arg, depth + 1) && readsKeys(alias, i),
1079
+ )
1080
+ : shapeOf(target(node)).some(n => anyKeyed(n, depth + 1));
1081
+ };
1082
+ return parts.some(
1083
+ /** @param {any} part */ part =>
1084
+ ((part.aliasTypeArguments ?? []).some(
1085
+ /** @type {(t: any, i: number) => boolean} */ (t, i) =>
1086
+ (t.flags & ts.TypeFlags.Any
1087
+ ? !isErrorType(ts, t)
1088
+ : depth < 4 && isAnyProps(ts, checker, t, depth + 1)) &&
1089
+ readsKeys(part.aliasSymbol?.declarations?.[0], i),
1090
+ ) ||
1091
+ shapeOf(part.aliasSymbol ?? part.symbol).some(n => anyKeyed(n, 0))) &&
1092
+ (checker.getIndexInfosOfType?.(part) ?? []).some(
1093
+ /** @param {any} info */ info => info.type.flags & ts.TypeFlags.Any,
1094
+ ),
1095
+ );
1096
+ }
1097
+
1098
+ /**
1099
+ * Is any part of a props type `any`, or built from a type the compiler could
1100
+ * not resolve (`Omit<Missing, 'x'>`, `Partial<Missing>`)? Then props it would
1101
+ * inherit are missing or unknown, and comparing would report documented
1102
+ * props as absent, or pass them unread.
1103
+ * @param {any} ts
1104
+ * @param {any} checker
1105
+ * @param {any} type
1106
+ * @param {number} depth
1107
+ * @param {Set<any>} seen types already read, so shared bases are read once
1108
+ * @returns {boolean}
1109
+ */
1110
+ function hasUnresolvedPart(ts, checker, type, depth, seen) {
1111
+ if (depth > 24 || seen.has(type)) return false;
1112
+ seen.add(type);
1113
+ if (type.flags & ts.TypeFlags.Any) return true;
1114
+ // A type made from another keeps what it was made from: an alias its
1115
+ // arguments, a generic reference its type arguments.
1116
+ const made = [
1117
+ ...(type.aliasTypeArguments ?? []),
1118
+ ...(type.objectFlags & ts.ObjectFlags.Reference
1119
+ ? checker.getTypeArguments(type)
1120
+ : []),
1121
+ ];
1122
+ if (made.some(/** @param {any} t */ t => isErrorType(ts, t))) return true;
1123
+ // A mapped type over one that does not resolve keeps no arguments behind a
1124
+ // named alias (`type Base = Pick<Missing, 'title'>`): its properties have
1125
+ // the compiler's error type.
1126
+ if (
1127
+ type.objectFlags & ts.ObjectFlags.Mapped &&
1128
+ checker
1129
+ .getPropertiesOfType(type)
1130
+ .some(
1131
+ /** @param {any} p */ p => isErrorType(ts, checker.getTypeOfSymbol(p)),
1132
+ )
1133
+ ) {
1134
+ return true;
1135
+ }
1136
+ // A mapped type written over one that does not resolve
1137
+ // (`{[K in keyof Missing]?: string}`) keeps it only in its declaration.
1138
+ const constraint = type.declaration?.typeParameter?.constraint;
1139
+ const mappedOver =
1140
+ constraint && ts.isTypeOperatorNode(constraint)
1141
+ ? constraint.type
1142
+ : constraint;
1143
+ if (
1144
+ type.objectFlags & ts.ObjectFlags.Mapped &&
1145
+ mappedOver &&
1146
+ isErrorType(ts, checker.getTypeFromTypeNode(mappedOver))
1147
+ ) {
1148
+ return true;
1149
+ }
1150
+ // A type mapped over one that does not resolve (`Omit<Missing, 'x'>`,
1151
+ // `Partial<Missing>`), reached directly, through a named alias, or nested,
1152
+ // reads as index signatures whose value is that unresolved type, which no
1153
+ // source declares.
1154
+ if (
1155
+ type.flags & ts.TypeFlags.Object &&
1156
+ (checker.getIndexInfosOfType?.(type) ?? []).some(
1157
+ /** @param {any} info */ info =>
1158
+ !info.declaration && isErrorType(ts, info.type),
1159
+ )
1160
+ ) {
1161
+ return true;
1162
+ }
1163
+ if (type.isUnion() || type.isIntersection()) {
1164
+ return type.types.some(
1165
+ /** @param {any} t */ t =>
1166
+ hasUnresolvedPart(ts, checker, t, depth + 1, seen),
1167
+ );
1168
+ }
1169
+ if (type.flags & ts.TypeFlags.Object) {
1170
+ const target =
1171
+ type.objectFlags & ts.ObjectFlags.Reference ? type.target : type;
1172
+ if (target.objectFlags & ts.ObjectFlags.ClassOrInterface) {
1173
+ // An unresolved `extends` is dropped from the base types, so read the
1174
+ // heritage clauses themselves.
1175
+ for (const declaration of target.symbol?.declarations ?? []) {
1176
+ for (const clause of declaration.heritageClauses ?? []) {
1177
+ for (const node of clause.types) {
1178
+ const base = checker.getTypeAtLocation(node);
1179
+ if (hasUnresolvedPart(ts, checker, base, depth + 1, seen))
1180
+ return true;
1181
+ }
1182
+ }
1183
+ }
1184
+ }
1185
+ }
1186
+ return false;
1187
+ }
1188
+
1189
+ /**
1190
+ * Compare each documented prop table with the TypeScript props of the export
1191
+ * it describes.
1192
+ * @param {PropDriftTable[]} tables
1193
+ * @param {{packageDir: string, resolveFrom: Array<string | null | undefined>}} options
1194
+ * @returns {PropDriftReport}
1195
+ */
1196
+ export function comparePropTables(tables, options) {
1197
+ const {packageDir, resolveFrom} = options;
1198
+ const compiler = resolveProjectTypeScript(resolveFrom);
1199
+ if (!compiler?.ts) {
1200
+ return {
1201
+ status: 'skipped',
1202
+ reason: compiler
1203
+ ? unusableTypeScriptReason(
1204
+ compiler.version,
1205
+ 'documented props were not compared with the code',
1206
+ )
1207
+ : TYPESCRIPT_MISSING_REASON,
1208
+ components: 0,
1209
+ findings: [],
1210
+ unchecked: [],
1211
+ };
1212
+ }
1213
+ const {ts, version} = compiler;
1214
+ let root = path.resolve(packageDir);
1215
+ try {
1216
+ root = fs.realpathSync(root);
1217
+ } catch {
1218
+ // Keep the resolved path.
1219
+ }
1220
+ const rel = (/** @type {string} */ file) =>
1221
+ path.relative(packageDir, file).split(path.sep).join('/');
1222
+
1223
+ /** @type {PropDriftUnchecked[]} */
1224
+ const unchecked = [];
1225
+ if (tables.length === 0) {
1226
+ return {
1227
+ status: 'checked',
1228
+ typescript: version,
1229
+ components: 0,
1230
+ findings: [],
1231
+ unchecked,
1232
+ };
1233
+ }
1234
+
1235
+ const project = readPackageTsconfig(
1236
+ ts,
1237
+ packageDir,
1238
+ tables.flatMap(table => table.sources),
1239
+ );
1240
+ if (project.error) {
1241
+ // Read without the package's own config, the types would be guesses.
1242
+ for (const table of tables) {
1243
+ unchecked.push({
1244
+ component: table.name,
1245
+ doc: table.doc,
1246
+ reason: `the package's TypeScript config has an error, so props were not read (${project.error})`,
1247
+ });
1248
+ }
1249
+ unchecked.sort((a, b) => a.component.localeCompare(b.component));
1250
+ return {
1251
+ status: 'checked',
1252
+ typescript: version,
1253
+ components: 0,
1254
+ findings: [],
1255
+ unchecked,
1256
+ };
1257
+ }
1258
+ const program = ts.createProgram({
1259
+ rootNames: [
1260
+ ...new Set([
1261
+ ...tables.flatMap(table => table.sources),
1262
+ ...project.declarations,
1263
+ ]),
1264
+ ],
1265
+ options: project.options,
1266
+ });
1267
+ const checker = program.getTypeChecker();
1268
+ const isOwnFile = ownFileTest(root);
1269
+ const ambient = unresolvedGlobals(
1270
+ ts,
1271
+ program,
1272
+ checker,
1273
+ project.declarations,
1274
+ project.options,
1275
+ isOwnFile,
1276
+ );
1277
+
1278
+ /** @type {PropDriftFinding[]} */
1279
+ const findings = [];
1280
+ /** @type {Array<PropDriftUnchecked & {props: string[]}>} */
1281
+ const propsNotChecked = [];
1282
+ let compared = 0;
1283
+ for (const table of tables) {
1284
+ /** @type {ReturnType<typeof readCodeProps> | null} */
1285
+ let read = null;
1286
+ let sourcePath = table.sources[0];
1287
+ for (const candidate of table.sources) {
1288
+ const attempt = readCodeProps(
1289
+ ts,
1290
+ program,
1291
+ checker,
1292
+ candidate,
1293
+ table.name,
1294
+ isOwnFile,
1295
+ ambient,
1296
+ );
1297
+ if (attempt.ok || read == null) {
1298
+ read = attempt;
1299
+ sourcePath = candidate;
1300
+ }
1301
+ if (attempt.ok) break;
1302
+ }
1303
+ if (read == null || !read.ok) {
1304
+ unchecked.push({
1305
+ component: table.name,
1306
+ doc: table.doc,
1307
+ reason:
1308
+ read != null && !read.ok
1309
+ ? read.reason
1310
+ : `no source file for ${table.name}`,
1311
+ });
1312
+ continue;
1313
+ }
1314
+ compared++;
1315
+ const source = rel(sourcePath);
1316
+ const documented = new Set();
1317
+ for (const raw of table.props) {
1318
+ if (!raw || typeof raw.name !== 'string') continue;
1319
+ const entries = documentedProps(raw);
1320
+ for (const entry of entries) {
1321
+ const propName = entry.name;
1322
+ if (entry.spread) continue;
1323
+ documented.add(propName);
1324
+ const code = read.props.get(propName);
1325
+ const base = {
1326
+ component: table.name,
1327
+ prop: entry.written,
1328
+ severity: /** @type {const} */ ('warning'),
1329
+ doc: table.doc,
1330
+ source,
1331
+ };
1332
+ if (entry.path.length > 0) {
1333
+ if (
1334
+ code
1335
+ ? fieldExists(ts, checker, code, entry.path)
1336
+ : read.accepts(propName)
1337
+ ) {
1338
+ continue;
1339
+ }
1340
+ findings.push({
1341
+ ...base,
1342
+ kind: 'not_in_code',
1343
+ message: code
1344
+ ? `"${entry.written}" is documented, but ${table.name}'s "${propName}" has no "${entry.path.join('.')}".`
1345
+ : `"${entry.written}" is documented, but ${table.name}'s props have no "${propName}".`,
1346
+ });
1347
+ continue;
1348
+ }
1349
+ if (!code) {
1350
+ if (read.accepts(propName)) continue;
1351
+ findings.push({
1352
+ ...base,
1353
+ kind: 'not_in_code',
1354
+ message: `"${propName}" is documented, but ${table.name}'s props have no "${propName}".`,
1355
+ });
1356
+ continue;
1357
+ }
1358
+ const docRequired = entry.required === true;
1359
+ if (docRequired !== code.required) {
1360
+ findings.push({
1361
+ ...base,
1362
+ kind: 'required_mismatch',
1363
+ message: code.required
1364
+ ? `"${propName}" is required in the code, but the doc does not mark it required.`
1365
+ : `"${propName}" is documented as required, but it is optional in the code.`,
1366
+ });
1367
+ }
1368
+ }
1369
+ }
1370
+ /** @type {string[]} */
1371
+ const untraced = [];
1372
+ for (const code of read.props.values()) {
1373
+ if (
1374
+ documented.has(code.name) ||
1375
+ code.skipTagged ||
1376
+ PROPS_NOT_DOCUMENTED.includes(code.name)
1377
+ ) {
1378
+ continue;
1379
+ }
1380
+ if (!code.own) {
1381
+ if (code.untraced) untraced.push(code.name);
1382
+ continue;
1383
+ }
1384
+ findings.push({
1385
+ component: table.name,
1386
+ prop: code.name,
1387
+ kind: 'not_in_doc',
1388
+ severity: 'warning',
1389
+ message: `${table.name} declares "${code.name}", but the doc does not list it.`,
1390
+ doc: table.doc,
1391
+ source,
1392
+ });
1393
+ }
1394
+ if (untraced.length > 0) {
1395
+ propsNotChecked.push({
1396
+ component: table.name,
1397
+ doc: table.doc,
1398
+ 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`,
1399
+ props: untraced.sort(),
1400
+ });
1401
+ }
1402
+ }
1403
+
1404
+ // Field by field: collation ignores a separator such as NUL, which would
1405
+ // sort one component's findings among another's that shares its prefix.
1406
+ findings.sort(
1407
+ (a, b) =>
1408
+ a.component.localeCompare(b.component) ||
1409
+ a.prop.localeCompare(b.prop) ||
1410
+ a.kind.localeCompare(b.kind),
1411
+ );
1412
+ unchecked.sort((a, b) => a.component.localeCompare(b.component));
1413
+ return {
1414
+ status: 'checked',
1415
+ typescript: version,
1416
+ components: compared,
1417
+ findings,
1418
+ unchecked,
1419
+ ...(propsNotChecked.length > 0 ? {propsNotChecked} : {}),
1420
+ };
1421
+ }