Skip to content

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

TypeScript

feat(cli): read a package's TypeScript project the way tsc reads it (#7681)

Joey1c6928388387
diff --git a/.changeset/doctor-typescript-project.md b/.changeset/doctor-typescript-project.md
new file mode 100644
index 0000000000..477d6b6ff8
--- /dev/null
+++ b/.changeset/doctor-typescript-project.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[chore] Internal groundwork for `astryx doctor integration components`: finding the project's own `typescript`, and reading a package's TypeScript project the way `tsc` reads it (its own `tsconfig.json` or a monorepo root's, a solution-style config's references, and the declaration files the config includes), and finding the references in that project the compiler cannot resolve. Nothing reaches it yet, so the CLI's behavior and output do not change.
+
+@josephfarina
diff --git a/packages/cli/foundation/discovery/package-tsconfig.mjs b/packages/cli/foundation/discovery/package-tsconfig.mjs
new file mode 100644
index 0000000000..c272f1c2f4
--- /dev/null
+++ b/packages/cli/foundation/discovery/package-tsconfig.mjs
@@ -0,0 +1,228 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Read a package's TypeScript project the way `tsc` reads it, so a
+ * check that reads the package's types with its own compiler sees what the
+ * package compiles against.
+ *
+ * - The config is the nearest `tsconfig.json`: the package's own, or a
+ * monorepo's root config for a local package. An app's config above an
+ * installed package (one below `node_modules`) is not the package's, and is
+ * not read.
+ * - A solution-style config (`"files": []` with `references`) lends the
+ * referenced config, at any depth, that includes the files to read.
+ * - The declaration files the config includes, included files that declare
+ * globals or augment a module, and included scripts (no import or export)
+ * join the files to read, so ambient types resolve as `tsc` resolves them.
+ * - Without a config, defaults read TSX the way bundlers do. A config with
+ * errors is reported, never read as defaults.
+ *
+ * @input The project's own `typescript`, the package directory, and the
+ * source files to read.
+ * @output Compiler options, the declaration files to add, and the config's
+ * error, if any.
+ * @position Foundation discovery, used by the documented-props comparison.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+
+/**
+ * Whether a file the config includes declares types every file sees: a
+ * declaration file, a file that declares globals or augments a module, or a
+ * script (a `.ts` file that TypeScript reads as no module).
+ * @param {any} ts
+ * @param {string} file
+ */
+function isAmbient(ts, file) {
+ if (/\.d\.[cm]?ts$/.test(file)) return true;
+ let text;
+ try {
+ text = fs.readFileSync(file, 'utf8');
+ } catch {
+ return false;
+ }
+ if (/\bdeclare\s+(?:global|module)\b/.test(text)) return true;
+ if (!/\.tsx?$/.test(file)) return false;
+ // Without the words, no module; with them, TypeScript decides.
+ return (
+ !/\b(?:import|export)\b/.test(text) ||
+ !ts.isExternalModule(
+ ts.createSourceFile(file, text, ts.ScriptTarget.Latest),
+ )
+ );
+}
+
+/**
+ * Read a config's `files` entries as `tsc` does, and report the first it
+ * cannot find. TypeScript itself substitutes `${configDir}` (on a version
+ * that has it), resolves each entry against the config that writes it, and
+ * tries the TypeScript extensions for one written without its own, so this
+ * cannot drift from `tsc`. The parsed file names then hold the files found.
+ * A file the `include` matched that is gone by the time it is read was
+ * another process's, and is not checked here.
+ * @param {any} ts
+ * @param {any} raw the config's JSON
+ * @param {string} configPath
+ * @param {any} config the parsed config, whose file names are updated
+ * @returns {string | null} the message `tsc` gives for the first entry it
+ * cannot find (TS6053, or TS6231 for a folder)
+ */
+function readFilesEntries(ts, raw, configPath, config) {
+ const literal = ts.parseJsonConfigFileContent(
+ raw,
+ {...ts.sys, readDirectory: () => []},
+ path.dirname(configPath),
+ undefined,
+ configPath,
+ ).fileNames;
+ if (literal.length === 0 || typeof ts.createProgram !== 'function') {
+ return null;
+ }
+ // Only the entries themselves: no library, no types, no imports.
+ const program = ts.createProgram({
+ rootNames: literal,
+ options: {
+ ...config.options,
+ noLib: true,
+ noResolve: true,
+ types: [],
+ noEmit: true,
+ },
+ });
+ const missing = program
+ .getOptionsDiagnostics()
+ .find(/** @param {any} d */ d => d.code === 6053 || d.code === 6231);
+ if (missing) {
+ const text = missing.messageText;
+ return typeof text === 'string' ? text : text.messageText;
+ }
+ const entries = new Set(
+ literal.map(/** @param {string} f */ f => path.resolve(f)),
+ );
+ config.fileNames = [
+ ...config.fileNames.filter(
+ /** @param {string} f */ f => !entries.has(path.resolve(f)),
+ ),
+ ...program.getSourceFiles().map(/** @param {any} sf */ sf => sf.fileName),
+ ];
+ return null;
+}
+
+/**
+ * @param {any} ts the project's own `typescript`
+ * @param {string} packageDir
+ * @param {string[]} sources the files to read
+ * @returns {{options: any, declarations: string[], error?: string}}
+ */
+export function readPackageTsconfig(ts, packageDir, sources) {
+ const defaults = {
+ jsx: ts.JsxEmit.ReactJSX,
+ target: ts.ScriptTarget.ES2022,
+ module: ts.ModuleKind.ESNext,
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
+ strict: true,
+ allowJs: true,
+ esModuleInterop: true,
+ resolveJsonModule: true,
+ allowImportingTsExtensions: true,
+ };
+ /** @type {string | undefined} */
+ let error;
+ /** @type {(configPath: string) => any} */
+ const parse = configPath => {
+ const read = ts.readConfigFile(configPath, ts.sys.readFile);
+ const config = read.error
+ ? {errors: [read.error], fileNames: [], options: {}}
+ : ts.parseJsonConfigFileContent(
+ read.config,
+ ts.sys,
+ path.dirname(configPath),
+ undefined,
+ configPath,
+ );
+ // "No inputs were found" is how a solution-style config reads.
+ const problem = config.errors.find(
+ /** @param {any} d */ d => d.code !== 18003,
+ );
+ const where = path.relative(packageDir, configPath);
+ if (problem) {
+ config.error = `${where}: ${ts.flattenDiagnosticMessageText(problem.messageText, ' ')}`;
+ } else if (!read.error) {
+ const missing = readFilesEntries(ts, read.config, configPath, config);
+ if (missing) {
+ // Paths read from the package, as the config's other errors are.
+ const dir = path.dirname(configPath).split(path.sep).join('/');
+ const rel = path.relative(packageDir, path.dirname(configPath));
+ config.error = `${where}: ${missing
+ .split(`${dir}/`)
+ .join(rel ? `${rel.split(path.sep).join('/')}/` : '')}`;
+ }
+ }
+ return config;
+ };
+ /** @type {any} */
+ let parsed;
+ try {
+ const found = ts.findConfigFile(
+ packageDir,
+ ts.sys.fileExists,
+ 'tsconfig.json',
+ );
+ // A config above the package is an app's when the package is installed
+ // below it (`node_modules`), and the package's own otherwise (a
+ // monorepo's root config, as `tsc` reads it).
+ const installed =
+ found &&
+ path
+ .relative(path.dirname(found), packageDir)
+ .split(path.sep)
+ .includes('node_modules');
+ parsed = found && !installed ? parse(found) : null;
+ const own = new Set(sources.map(file => path.resolve(file)));
+ /** @type {(config: any) => boolean} */
+ const includes = config =>
+ config.fileNames.some(
+ /** @param {string} file */ file => own.has(path.resolve(file)),
+ );
+ // Every reference, at any depth, each config once (a cycle ends). One
+ // that is missing or doesn't parse is the project's error when no config
+ // includes the sources, as `tsc` reports it.
+ const visited = new Set(found ? [path.resolve(found)] : []);
+ /** @type {any} */
+ let broken = null;
+ /** @type {(config: any) => any} */
+ const including = config => {
+ if (includes(config)) return config;
+ for (const ref of config.projectReferences ?? []) {
+ const next = path.resolve(ts.resolveProjectReferencePath(ref));
+ if (visited.has(next)) continue;
+ visited.add(next);
+ const referenced = parse(next);
+ if (referenced.error) broken ??= referenced;
+ const hit = including(referenced);
+ if (hit) return hit;
+ }
+ return null;
+ };
+ if (parsed) parsed = including(parsed) ?? broken ?? parsed;
+ } catch {
+ parsed = null;
+ }
+ error = parsed?.error;
+ const options = parsed ? {...parsed.options} : defaults;
+ if (options.jsx == null) options.jsx = defaults.jsx;
+ return {
+ options: {
+ ...options,
+ noEmit: true,
+ skipLibCheck: true,
+ incremental: false,
+ composite: false,
+ },
+ ...(error ? {error} : {}),
+ declarations: (parsed?.fileNames ?? []).filter(
+ /** @param {string} file */ file => isAmbient(ts, file),
+ ),
+ };
+}
diff --git a/packages/cli/foundation/discovery/package-tsconfig.test.mjs b/packages/cli/foundation/discovery/package-tsconfig.test.mjs
new file mode 100644
index 0000000000..a7f70cc30b
--- /dev/null
+++ b/packages/cli/foundation/discovery/package-tsconfig.test.mjs
@@ -0,0 +1,210 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file readPackageTsconfig(): the package's own config, a solution-style
+ * config's references, a monorepo root's config for a local package but not
+ * an app's above an installed one, ambient declaration files, and a config
+ * with errors.
+ */
+
+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 {readPackageTsconfig} from './package-tsconfig.mjs';
+
+const require = createRequire(import.meta.url);
+const ts = require('typescript');
+
+/** @type {string} */
+let root;
+
+beforeEach(() => {
+ root = fs.realpathSync(
+ fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-tsconfig-')),
+ );
+});
+
+afterEach(() => {
+ fs.rmSync(root, {recursive: true, force: true});
+});
+
+/**
+ * @param {string} rel
+ * @param {string | object} content
+ */
+function write(rel, content) {
+ const file = path.join(root, rel);
+ fs.mkdirSync(path.dirname(file), {recursive: true});
+ fs.writeFileSync(
+ file,
+ typeof content === 'string' ? content : JSON.stringify(content),
+ );
+ return file;
+}
+
+const OPTIONS = {strict: true, jsx: 'react-jsx', paths: {'@/*': ['./src/*']}};
+
+describe('readPackageTsconfig', () => {
+ it('reads defaults without a config, and the config the package has, with the declaration files it includes', () => {
+ const source = write('src/Button.tsx', 'export {};\n');
+ const defaults = readPackageTsconfig(ts, root, [source]);
+ expect(defaults.options).toMatchObject({
+ jsx: ts.JsxEmit.ReactJSX,
+ strict: true,
+ noEmit: true,
+ });
+ expect(defaults.declarations).toEqual([]);
+ expect(defaults.error).toBeUndefined();
+
+ write('tsconfig.json', {
+ compilerOptions: OPTIONS,
+ include: ['src', 'types'],
+ });
+ const ambient = write('types/ambient.d.ts', 'interface A {}\n');
+ const global = write('src/global.ts', 'declare global {}\nexport {};\n');
+ // A script (no import or export) declares globals too, an `export`
+ // inside its namespace included.
+ const script = write('types/props.ts', 'interface ScriptProps {}\n');
+ const namespace = write(
+ 'types/acme.ts',
+ 'declare namespace Acme {\n export interface Props {}\n}\n',
+ );
+ write('src/module.ts', 'export interface ModuleProps {}\n');
+
+ const own = readPackageTsconfig(ts, root, [source]);
+
+ expect(own.options.paths).toEqual(OPTIONS.paths);
+ expect(own.declarations.sort()).toEqual(
+ [global, ambient, script, namespace].sort(),
+ );
+ });
+
+ it("follows a solution-style config's references, at any depth and through a cycle, to the config that includes the sources", () => {
+ const source = write('src/Button.tsx', 'export {};\n');
+ const chain = [
+ 'tsconfig.json',
+ 'l1.json',
+ 'l2.json',
+ 'l3.json',
+ 'l4.json',
+ 'l5.json',
+ ];
+ chain.forEach((file, i) =>
+ write(file, {
+ files: [],
+ // Each level also refers back to the root, a cycle tsc rejects but
+ // the walk must not loop on.
+ references: [
+ {path: `./${chain[i + 1] ?? 'app.json'}`},
+ {path: './tsconfig.json'},
+ ],
+ }),
+ );
+ write('app.json', {compilerOptions: OPTIONS, include: ['src']});
+
+ const project = readPackageTsconfig(ts, root, [source]);
+
+ expect(project.error).toBeUndefined();
+ expect(project.options.paths).toEqual(OPTIONS.paths);
+
+ // A reference that is missing or doesn't parse, when no config includes
+ // the sources, is the project's error, as `tsc` reports it.
+ write('tsconfig.json', {files: [], references: [{path: './gone.json'}]});
+ expect(readPackageTsconfig(ts, root, [source]).error).toMatch(
+ /^gone\.json: .*gone\.json/,
+ );
+ write('broken.json', '{"compilerOptions": ');
+ write('tsconfig.json', {files: [], references: [{path: './broken.json'}]});
+ expect(readPackageTsconfig(ts, root, [source]).error).toMatch(
+ /^broken\.json: /,
+ );
+ });
+
+ it("reads a monorepo root's config for a local package, and not an app's config for a package installed below it", () => {
+ write('tsconfig.json', {compilerOptions: OPTIONS});
+ const local = path.join(root, 'packages', 'local');
+ const installed = path.join(root, 'node_modules', '@acme', 'widgets');
+ const localSource = write('packages/local/src/Button.tsx', 'export {};\n');
+ const installedSource = write(
+ 'node_modules/@acme/widgets/src/Button.tsx',
+ 'export {};\n',
+ );
+
+ expect(readPackageTsconfig(ts, local, [localSource]).options.paths).toEqual(
+ OPTIONS.paths,
+ );
+ expect(
+ readPackageTsconfig(ts, installed, [installedSource]).options.paths,
+ ).toBeUndefined();
+ });
+
+ it('reports a config with errors instead of reading defaults', () => {
+ const source = write('src/Button.tsx', 'export {};\n');
+ write('tsconfig.json', {files: ['src/Button.tsx', 'src/missing.ts']});
+ expect(readPackageTsconfig(ts, root, [source]).error).toMatch(
+ /^tsconfig\.json: .*src\/missing\.ts.* not found/,
+ );
+
+ write('tsconfig.json', {extends: './missing-base.json'});
+ expect(readPackageTsconfig(ts, root, [source]).error).toMatch(
+ /^tsconfig\.json: .*missing-base\.json/,
+ );
+
+ write('tsconfig.json', '{"compilerOptions": ');
+ expect(readPackageTsconfig(ts, root, [source]).error).toMatch(
+ /^tsconfig\.json: /,
+ );
+ });
+
+ it('reads each `files` entry as `tsc` finds it', () => {
+ const source = write('src/Button.tsx', 'export {};\n');
+ write('src/Card.ts', 'export {};\n');
+ write('types/globals.ts', 'interface AcmeGlobal { tone?: string }\n');
+ write('configs/base.json', {files: ['${configDir}/src/Button.tsx']});
+ /** @type {(config: object) => any} */
+ const read = config => {
+ write('tsconfig.json', {compilerOptions: OPTIONS, ...config});
+ return readPackageTsconfig(ts, root, [source]);
+ };
+
+ // `${configDir}`, written in the package's config or in a shared base it
+ // extends, and an entry without its extension compile with `tsc -p`.
+ expect(
+ read({files: ['${configDir}/src/Button.tsx']}).error,
+ ).toBeUndefined();
+ expect(read({extends: './configs/base.json'}).error).toBeUndefined();
+ const bare = read({files: ['src/Button', 'src/Card', 'types/globals']});
+ expect(bare.error).toBeUndefined();
+ expect(bare.declarations).toEqual([path.join(root, 'types', 'globals.ts')]);
+
+ // An entry `tsc` can't find is an error: a missing file (TS6053), and a
+ // folder (TS6231).
+ expect(read({files: ['src/Button.tsx', 'src/gone.ts']}).error).toMatch(
+ /^tsconfig\.json: File 'src\/gone\.ts' not found\.$/,
+ );
+ expect(read({files: ['src']}).error).toMatch(
+ /^tsconfig\.json: Could not resolve the path 'src' with the extensions/,
+ );
+ });
+
+ it('reports only a missing `files` entry, not a file the `include` matched that is gone by the time it is read', () => {
+ const source = write('src/Button.tsx', 'export {};\n');
+ write('tsconfig.json', {compilerOptions: OPTIONS, include: ['src']});
+ // A file another process writes and removes while the config is read.
+ const gone = path.join(root, 'src', 'gone.ts');
+ const racing = {
+ ...ts,
+ sys: {
+ ...ts.sys,
+ readDirectory: (/** @type {any[]} */ ...args) => [
+ ...ts.sys.readDirectory(...args),
+ gone,
+ ],
+ },
+ };
+
+ expect(readPackageTsconfig(racing, root, [source]).error).toBeUndefined();
+ });
+});
diff --git a/packages/cli/foundation/discovery/project-typescript.mjs b/packages/cli/foundation/discovery/project-typescript.mjs
new file mode 100644
index 0000000000..a5108a0225
--- /dev/null
+++ b/packages/cli/foundation/discovery/project-typescript.mjs
@@ -0,0 +1,61 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Find the project's own TypeScript compiler.
+ *
+ * @input Directories to resolve `typescript` from, in order.
+ * @output The compiler module and its version; or, when the only TypeScript
+ * installed has no JavaScript compiler API to read types with, its version
+ * alone; or null when none is installed.
+ * @position Shared by the author checks that read source with the project's
+ * compiler, so each finds it, and says why it cannot use it, the same way.
+ */
+
+import * as path from 'node:path';
+import {createRequire} from 'node:module';
+
+/**
+ * Resolve the project's own `typescript`, trying each directory in order.
+ * @param {Array<string | null | undefined>} dirs
+ * @returns {{ts: any, version: string} | {ts: null, version: string} | null}
+ * `ts: null` when a TypeScript is installed but has no `createProgram`
+ */
+export function resolveProjectTypeScript(dirs) {
+ /** @type {string | null} */
+ let unusable = null;
+ for (const dir of dirs) {
+ if (!dir) continue;
+ const require = createRequire(path.join(path.resolve(dir), 'package.json'));
+ /** The version of the `typescript` package installed here, or null. */
+ const installed = () => {
+ try {
+ const {version} = require('typescript/package.json');
+ return typeof version === 'string' && version !== '' ? version : null;
+ } catch {
+ return null;
+ }
+ };
+ try {
+ const ts = require('typescript');
+ if (ts && typeof ts.createProgram === 'function') {
+ return {ts, version: String(ts.version)};
+ }
+ unusable ??= installed();
+ } catch {
+ // Not installed from here, or installed without an entry this CLI can
+ // load; try the next directory.
+ unusable ??= installed();
+ }
+ }
+ return unusable ? {ts: null, version: unusable} : null;
+}
+
+/**
+ * Why a check that needs the compiler did not run, when the TypeScript
+ * installed has no JavaScript compiler API.
+ * @param {string} version
+ * @param {string} outcome what was not done, such as `docs were not checked`
+ */
+export function unusableTypeScriptReason(version, outcome) {
+ return `TypeScript ${version} is installed in this project, but it has no JavaScript compiler API (\`createProgram\`) to read types with, so ${outcome}.`;
+}
diff --git a/packages/cli/foundation/discovery/unresolved-references.mjs b/packages/cli/foundation/discovery/unresolved-references.mjs
new file mode 100644
index 0000000000..9f3a2d73a6
--- /dev/null
+++ b/packages/cli/foundation/discovery/unresolved-references.mjs
@@ -0,0 +1,790 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Find the references in a package's TypeScript project that the
+ * compiler cannot resolve, so a check that reads the package's types knows
+ * when part of them is a guess: a dependency that is not installed can make
+ * any type built from it the compiler's error type, whatever the code looks
+ * like.
+ *
+ * - From given files: their imports, re-exports, `/// <reference>`
+ * directives and side-effect imports, and the files those reach in turn;
+ * and in the package's own files, each type the compiler can only give its
+ * error type.
+ * - From the program's global roots: the package's own declaration files
+ * that act globally and the type packages the program loads by name
+ * (`compilerOptions.types`).
+ *
+ * @input The project's own `typescript`, a program and its checker.
+ * @output The first reference that does not resolve, or null.
+ * @position Foundation discovery, used by the documented-props comparison.
+ */
+
+import * as path from 'node:path';
+
+/**
+ * What the walk learns about one program for one `mine`: each source file's
+ * references (the first that doesn't resolve, the first type it can't give,
+ * the files they reach), what each declaration's type is inferred from, and
+ * the declarations whose whole reach reads clean. Each is a fact about the
+ * program, so an answer never depends on what an earlier call read; the
+ * record goes when the program does.
+ * @type {WeakMap<any, WeakMap<Function, {files: Map<any, any>, local: Map<any, any>, clean: Set<any>, untypedNames: Map<any, Set<string>>, errors: Map<any, any[]>}>>}
+ */
+const PROGRAMS = new WeakMap();
+
+/**
+ * @typedef {object} UnresolvedReference
+ * @property {string} name the reference as written, quoted
+ * @property {string} file the file that writes it
+ * @property {'imported' | 'used' | 'named'} how a file imports it, a file
+ * uses it as a type name, or the config names it
+ */
+
+/**
+ * The JSDoc tags whose types the compiler reads in a JavaScript file, in the
+ * TypeScript versions that have them. It never checks the others (`@throws`,
+ * `@exception`, `@see`, `@example` …), so a name declared nowhere in one
+ * decides no type.
+ */
+const TYPED_JSDOC_TAGS = [
+ 'JSDocTypeTag',
+ 'JSDocParameterTag',
+ 'JSDocReturnTag',
+ 'JSDocTypedefTag',
+ 'JSDocCallbackTag',
+ 'JSDocTemplateTag',
+ 'JSDocPropertyTag',
+ 'JSDocThisTag',
+ 'JSDocEnumTag',
+ 'JSDocAugmentsTag',
+ 'JSDocImplementsTag',
+ 'JSDocSatisfiesTag',
+ 'JSDocOverloadTag',
+ 'JSDocImportTag',
+];
+
+/**
+ * The first reference that does not resolve from the given files, the files
+ * they import, and so on, as far as `follow` allows. A reference fails when
+ * the program finds no module, no type package or no file for it, when a
+ * module does not export a name imported from it, or, in the files `mine`
+ * accepts, when a type name resolves to no declaration (TS2304). A module
+ * found without types (a JavaScript file) resolves: its names are `any`. A
+ * side-effect import counts where the compiler checks one
+ * (`noUncheckedSideEffectImports`, on by default from TypeScript 6).
+ * @param {any} ts the project's own `typescript`
+ * @param {any} program
+ * @param {any} checker
+ * @param {any[]} roots source files
+ * @param {(file: string) => boolean} follow which files it reads past them
+ * @param {(file: string) => boolean} mine whose type names it checks
+ * @returns {UnresolvedReference | null}
+ */
+export function unresolvedReference(ts, program, checker, roots, follow, mine) {
+ const K = ts.SyntaxKind;
+ const typedTags = new Set(
+ TYPED_JSDOC_TAGS.map(name => K[name]).filter(kind => kind !== undefined),
+ );
+ const STARTS = new Set([
+ K.TypeReference,
+ K.TypeQuery,
+ K.IndexedAccessType,
+ K.ImportType,
+ K.ExpressionWithTypeArguments,
+ ]);
+ const options = program.getCompilerOptions();
+ const sideEffects =
+ options.noUncheckedSideEffectImports ??
+ Number.parseInt(ts.versionMajorMinor, 10) >= 6;
+ let byMine = PROGRAMS.get(program);
+ if (!byMine) {
+ byMine = new WeakMap();
+ PROGRAMS.set(program, byMine);
+ }
+ let state = byMine.get(mine);
+ if (!state) {
+ state = {
+ files: new Map(),
+ local: new Map(),
+ clean: new Set(),
+ untypedNames: new Map(),
+ errors: new Map(),
+ };
+ byMine.set(mine, state);
+ }
+ const record = state;
+ /**
+ * The names a file imports from modules found without types.
+ * @type {(file: any) => Set<string>}
+ */
+ const untypedNamesOf = file => {
+ let names = record.untypedNames.get(file);
+ if (names) return names;
+ names = new Set();
+ for (const literal of file.imports ?? []) {
+ if (literal.pos < 0 || checker.getSymbolAtLocation(literal)) continue;
+ if (
+ ts.resolveModuleName(literal.text, file.fileName, options, ts.sys)
+ .resolvedModule
+ ) {
+ for (const name of boundNames(ts, literal.parent)) names.add(name);
+ }
+ }
+ record.untypedNames.set(file, names);
+ return names;
+ };
+ /**
+ * Whether `tsc` reports an error inside a node. It leaves a line
+ * `@ts-expect-error` covers alone, and a `@ts-nocheck` file, and without
+ * `noImplicitAny` it gives some reads the error type with no diagnostic.
+ * @type {(file: any, node: any) => boolean}
+ */
+ const errorReported = (file, node) => {
+ const errors =
+ record.errors.get(file) ??
+ program
+ .getSemanticDiagnostics(file)
+ .filter(
+ (/** @type {any} */ d) => d.category === ts.DiagnosticCategory.Error,
+ );
+ record.errors.set(file, errors);
+ const start = node.getStart(file);
+ return errors.some(
+ (/** @type {any} */ d) =>
+ d.start !== undefined && d.start >= start && d.start < node.end,
+ );
+ };
+ /**
+ * Whether a function's type comes from overload signatures.
+ * @type {(fn: any) => boolean}
+ */
+ const overloaded = fn => {
+ const symbol = fn.name && checker.getSymbolAtLocation(fn.name);
+ return (symbol?.declarations ?? []).some(
+ (/** @type {any} */ d) => d !== fn && ts.isFunctionLike(d) && !d.body,
+ );
+ };
+ /**
+ * The expressions a declaration's type is inferred from: an initializer
+ * with no type written, what a function returns when its return type
+ * isn't written, and a parameter's default. A class's names come from
+ * its written members and its base; a member's type is read where a type
+ * indexes it. A type written down, or overloads, decide it alone.
+ * @type {(declaration: any) => any[]}
+ */
+ const typeSources = declaration => {
+ /** @type {any[]} */
+ const sources = [];
+ const fromFunction = (/** @type {any} */ fn) => {
+ if (overloaded(fn)) return;
+ for (const parameter of fn.parameters ?? []) {
+ if (!parameter.type && parameter.initializer) {
+ sources.push(parameter.initializer);
+ }
+ }
+ if (fn.type || !fn.body) return;
+ if (!ts.isBlock(fn.body)) {
+ sources.push(fn.body);
+ return;
+ }
+ // A function or class nested in the body returns for itself.
+ const visit = (/** @type {any} */ n) => {
+ if (ts.isFunctionLike(n) || ts.isClassLike(n)) return;
+ if (ts.isReturnStatement(n) && n.expression) sources.push(n.expression);
+ ts.forEachChild(n, visit);
+ };
+ ts.forEachChild(fn.body, visit);
+ };
+ if (ts.isFunctionLike(declaration)) {
+ fromFunction(declaration);
+ } else if (ts.isClassLike(declaration)) {
+ for (const clause of declaration.heritageClauses ?? []) {
+ if (clause.token === ts.SyntaxKind.ExtendsKeyword) {
+ for (const base of clause.types) sources.push(base.expression);
+ }
+ }
+ } else if (ts.isBindingElement(declaration)) {
+ if (declaration.initializer) sources.push(declaration.initializer);
+ let root = declaration.parent;
+ while (root && !ts.isVariableDeclaration(root) && !ts.isParameter(root)) {
+ root = root.parent;
+ }
+ if (root && !root.type && root.initializer) {
+ sources.push(root.initializer);
+ }
+ } else if (!declaration.type && declaration.initializer) {
+ sources.push(declaration.initializer);
+ }
+ return sources;
+ };
+ /**
+ * What one declaration's type is inferred from, read on its own: the
+ * first value read there that the compiler can only give its error type
+ * and `tsc` reports, and the declarations it names, whose types count
+ * too.
+ * @type {(declaration: any) => {found: {node: any, file: any} | null, names: any[]}}
+ */
+ const localScan = declaration => {
+ const known = record.local.get(declaration);
+ if (known) return known;
+ const file = declaration.getSourceFile();
+ const untypedHere = untypedNamesOf(file);
+ /** @type {any[]} */
+ const names = [];
+ /** @type {{node: any, file: any} | null} */
+ let found = null;
+ /** @type {(node: any) => void} */
+ const scan = node => {
+ if (found) return;
+ // A JSX element is a `JSX.Element`, whatever it holds.
+ if (
+ ts.isJsxElement(node) ||
+ ts.isJsxSelfClosingElement(node) ||
+ ts.isJsxFragment(node)
+ ) {
+ return;
+ }
+ // A cast that writes the type decides it, whatever the value.
+ if (
+ (ts.isAsExpression(node) || ts.isTypeAssertionExpression(node)) &&
+ !ts.isConstTypeReference(node.type)
+ ) {
+ return;
+ }
+ if (ts.isFunctionLike(node) || ts.isClassLike(node)) {
+ for (const source of typeSources(node)) scan(source);
+ return;
+ }
+ ts.forEachChild(node, scan);
+ if (found) return;
+ if (
+ readsValue(ts, node) &&
+ !untypedHere.has(rootName(ts, node)) &&
+ isErrorValue(checker, node) &&
+ errorReported(file, node)
+ ) {
+ found = {node, file};
+ return;
+ }
+ // A name for another declaration: its type comes from there.
+ if (!ts.isIdentifier(node)) return;
+ let symbol =
+ ts.isShorthandPropertyAssignment(node.parent) &&
+ node.parent.name === node
+ ? checker.getShorthandAssignmentValueSymbol(node.parent)
+ : checker.getSymbolAtLocation(node);
+ if (symbol && symbol.flags & ts.SymbolFlags.Alias) {
+ symbol = checker.getAliasedSymbol(symbol);
+ }
+ for (const named of symbol?.declarations ?? []) {
+ if (!names.includes(named)) names.push(named);
+ }
+ };
+ for (const source of typeSources(declaration)) {
+ scan(source);
+ if (found) break;
+ }
+ const result = {found, names};
+ record.local.set(declaration, result);
+ return result;
+ };
+ /**
+ * The first such read in what the declarations' types are inferred from,
+ * in the package's own TypeScript files, following the declarations each
+ * names, depth first. A declaration whose whole reach read clean before
+ * is skipped, which changes no answer.
+ * @type {(declarations: readonly any[]) => {node: any, file: any} | null}
+ */
+ const scanDeclarations = declarations => {
+ const visited = new Set();
+ /** @type {(list: readonly any[]) => {node: any, file: any} | null} */
+ const walk = list => {
+ for (const declaration of list) {
+ const file = declaration.getSourceFile();
+ if (
+ visited.has(declaration) ||
+ record.clean.has(declaration) ||
+ file.isDeclarationFile ||
+ !/\.[cm]?tsx?$/.test(file.fileName) ||
+ !mine(file.fileName)
+ ) {
+ continue;
+ }
+ visited.add(declaration);
+ const {found, names} = localScan(declaration);
+ const reached = found ?? walk(names);
+ if (reached) return reached;
+ }
+ return null;
+ };
+ const found = walk(declarations);
+ if (!found)
+ for (const declaration of visited) record.clean.add(declaration);
+ return found;
+ };
+ /** @type {(sf: any) => {missing: UnresolvedReference | null, untyped: UnresolvedReference | null, next: any[]}} */
+ const read = sf => {
+ const cache = record.files;
+ if (cache.has(sf)) return cache.get(sf);
+ /** @type {UnresolvedReference | null} */
+ let missing = null;
+ /** @type {any[]} */
+ const next = [];
+ /** @type {(name: string, how?: UnresolvedReference['how']) => void} */
+ const fail = (name, how = 'imported') => {
+ missing ??= {name, file: sf.fileName, how};
+ };
+ // A module found without types gives its names no types: they are
+ // `any`, not missing.
+ /** @type {Set<string>} */
+ const untypedNames = new Set();
+ for (const literal of sf.imports ?? []) {
+ const parent = literal.parent;
+ // The JSX runtime import the compiler adds itself shapes no types.
+ if (!parent || missing || literal.pos < 0) continue;
+ if (
+ ts.isImportDeclaration(parent) &&
+ !parent.importClause &&
+ !sideEffects
+ ) {
+ continue;
+ }
+ const module = checker.getSymbolAtLocation(literal);
+ if (!module) {
+ const found = ts.resolveModuleName(
+ literal.text,
+ sf.fileName,
+ options,
+ ts.sys,
+ ).resolvedModule;
+ if (!found) fail(`\`${literal.text}\``);
+ else for (const name of boundNames(ts, parent)) untypedNames.add(name);
+ continue;
+ }
+ for (const d of module.declarations ?? []) next.push(d.getSourceFile());
+ // Each name an import or a re-export takes from the module. One it
+ // does not export resolves to the compiler's `unknown` symbol.
+ const clause = ts.isImportDeclaration(parent)
+ ? parent.importClause
+ : null;
+ const bound = clause?.namedBindings;
+ const exported = ts.isExportDeclaration(parent)
+ ? parent.exportClause
+ : null;
+ const names = [
+ ...(clause?.name ? [clause.name] : []),
+ ...(bound && ts.isNamedImports(bound) ? bound.elements : []),
+ ...(exported && ts.isNamedExports(exported) ? exported.elements : []),
+ ].map(/** @param {any} n */ n => n.name ?? n);
+ for (const name of names) {
+ const alias = checker.getSymbolAtLocation(name);
+ const resolved = alias && checker.getAliasedSymbol(alias);
+ if (
+ !resolved ||
+ (resolved.escapedName === 'unknown' && !resolved.declarations?.length)
+ ) {
+ fail(`\`${name.text}\` from \`${literal.text}\``);
+ }
+ }
+ }
+ for (const ref of sf.typeReferenceDirectives ?? []) {
+ const found = ts.resolveTypeReferenceDirective(
+ ref.fileName,
+ sf.fileName,
+ options,
+ ts.sys,
+ ).resolvedTypeReferenceDirective?.resolvedFileName;
+ if (!found) fail(`the types \`${ref.fileName}\``);
+ else if (program.getSourceFile(found)) {
+ next.push(program.getSourceFile(found));
+ }
+ }
+ for (const ref of sf.referencedFiles ?? []) {
+ const file = path.resolve(path.dirname(sf.fileName), ref.fileName);
+ const found = ['', '.ts', '.tsx', '.d.ts']
+ .map(ext => program.getSourceFile(file + ext))
+ .find(Boolean);
+ if (found) next.push(found);
+ else fail(`\`${ref.fileName}\``);
+ }
+ // A type the compiler can only give its error type: a name or value
+ // declared nowhere, a property that doesn't exist. `keyof` or a template
+ // literal key over one hides the error, so it is found where it starts.
+ // `as const` is a type reference named `const`. A JavaScript file's
+ // JSDoc types count too, in the tags the compiler reads types from;
+ // TypeScript reads no types from a `.ts` file's.
+ /** @type {UnresolvedReference | null} */
+ let untyped = null;
+ const js = /\.[cm]?jsx?$/.test(sf.fileName);
+ // A name, or an `import()` type, from a module found without types.
+ /** @type {(node: any) => boolean} */
+ const fromUntyped = node => {
+ if (ts.isImportTypeNode(node)) {
+ const literal = node.argument?.literal;
+ return (
+ !!literal &&
+ ts.isStringLiteral(literal) &&
+ !checker.getSymbolAtLocation(literal) &&
+ !!ts.resolveModuleName(literal.text, sf.fileName, options, ts.sys)
+ .resolvedModule
+ );
+ }
+ let name = ts.isTypeQueryNode(node)
+ ? node.exprName
+ : ts.isTypeReferenceNode(node)
+ ? node.typeName
+ : null;
+ while (name && ts.isQualifiedName(name)) name = name.left;
+ return !!name && ts.isIdentifier(name) && untypedNames.has(name.text);
+ };
+ // A value `typeof` reads, or a class a type names, in a TypeScript file
+ // of the package's own, whose type is inferred from a value the compiler
+ // can't type: a property that doesn't exist, spread into an object,
+ // turns it `any`, so `keyof typeof` it takes any name. Only an error
+ // `tsc` reports counts.
+ /** @type {(name: any, classes?: boolean) => boolean} */
+ const readsErrorValue = (name, classes = false) => {
+ let target = checker.getSymbolAtLocation(name);
+ if (target && target.flags & ts.SymbolFlags.Alias) {
+ target = checker.getAliasedSymbol(target);
+ }
+ const declarations = (target?.declarations ?? []).filter(
+ (/** @type {any} */ d) => !classes || ts.isClassLike(d),
+ );
+ const found = scanDeclarations(declarations);
+ if (found) {
+ untyped = {
+ name: `\`${oneLine(found.node.getText(found.file))}\``,
+ file: found.file.fileName,
+ how: 'used',
+ };
+ }
+ return false;
+ };
+ // The members a type indexes, such as `Store['slots']`: a member's
+ // type is inferred from its own initializer or body.
+ /** @type {(node: any) => boolean} */
+ const readsIndexedMembers = node => {
+ const object = checker.getTypeFromTypeNode(node.objectType);
+ const index = checker.getTypeFromTypeNode(node.indexType);
+ const keys = (index.isUnion() ? index.types : [index]).filter(
+ (/** @type {any} */ key) =>
+ key.isStringLiteral() || key.isNumberLiteral(),
+ );
+ const members = keys.map((/** @type {any} */ key) =>
+ checker.getPropertyOfType(object, String(key.value)),
+ );
+ const found = scanDeclarations(
+ members.flatMap(
+ (/** @type {any} */ member) => member?.declarations ?? [],
+ ),
+ );
+ if (found) {
+ untyped = {
+ name: `\`${oneLine(found.node.getText(found.file))}\``,
+ file: found.file.fileName,
+ how: 'used',
+ };
+ }
+ return false;
+ };
+ // A class's base, in its `extends` clause or a JavaScript file's
+ // `@augments` tag, that names nothing: the compiler can give the class no
+ // type, so it has no props to read. A base that resolves is read as a
+ // value below.
+ /** @type {(node: any) => boolean} */
+ const baseless = node =>
+ isValueWithTypeArguments(ts, node) &&
+ (ts.isHeritageClause(node.parent) ||
+ ts.isJSDocAugmentsTag(node.parent)) &&
+ ts.isEntityNameExpression(node.expression) &&
+ !checker.getSymbolAtLocation(node.expression);
+ // The innermost such type names it: its parts are read first.
+ /** @type {(node: any) => void} */
+ const visit = node => {
+ if (untyped) return;
+ for (const doc of js ? (node.jsDoc ?? []) : []) {
+ for (const tag of doc.tags ?? []) {
+ if (typedTags.has(tag.kind)) visit(tag);
+ }
+ }
+ ts.forEachChild(node, visit);
+ if (!untyped && baseless(node)) {
+ untyped = {
+ name: `\`${node.expression.getText(sf)}\``,
+ file: sf.fileName,
+ how: 'used',
+ };
+ }
+ if (
+ !untyped &&
+ ((STARTS.has(node.kind) &&
+ !(ts.isTypeReferenceNode(node) && ts.isConstTypeReference(node)) &&
+ !isValueWithTypeArguments(ts, node) &&
+ !fromUntyped(node) &&
+ isErrorType(checker, node)) ||
+ (ts.isTypeQueryNode(node) && readsErrorValue(node.exprName)) ||
+ (ts.isIndexedAccessTypeNode(node) && readsIndexedMembers(node)) ||
+ // A class a type names: its instance type is inferred too.
+ (ts.isTypeReferenceNode(node) &&
+ readsErrorValue(node.typeName, true)) ||
+ (ts.isExpressionWithTypeArguments(node) &&
+ readsErrorValue(node.expression, true)))
+ ) {
+ untyped = {
+ name: `\`${node.getText(sf)}\``,
+ file: sf.fileName,
+ how: 'used',
+ };
+ }
+ };
+ if (!missing && mine(sf.fileName)) visit(sf);
+ const entry = {missing, untyped, next};
+ cache.set(sf, entry);
+ return entry;
+ };
+ // A reference that doesn't resolve, anywhere the walk goes, names what to
+ // install; a type the compiler can't give is often only where it shows.
+ /** @type {UnresolvedReference | null} */
+ let firstUntyped = null;
+ const seen = new Set();
+ const queue = roots.filter(Boolean);
+ while (queue.length > 0) {
+ const sf = queue.shift();
+ if (seen.has(sf)) continue;
+ seen.add(sf);
+ const {missing, untyped, next} = read(sf);
+ if (missing) return missing;
+ firstUntyped ??= untyped;
+ queue.push(...next.filter(file => follow(file.fileName)));
+ }
+ return firstUntyped;
+}
+
+/**
+ * The local names an import binds: its default, its namespace, the names it
+ * lists, or an `import x = require()`.
+ * @param {any} ts
+ * @param {any} parent the import's declaration
+ * @returns {string[]}
+ */
+function boundNames(ts, parent) {
+ if (ts.isExternalModuleReference(parent)) return [parent.parent.name.text];
+ const clause = ts.isImportDeclaration(parent) ? parent.importClause : null;
+ const bound = clause?.namedBindings;
+ return [
+ ...(clause?.name ? [clause.name.text] : []),
+ ...(bound && ts.isNamespaceImport(bound) ? [bound.name.text] : []),
+ ...(bound && ts.isNamedImports(bound)
+ ? bound.elements.map(/** @param {any} e */ e => e.name.text)
+ : []),
+ ];
+}
+
+/**
+ * Whether an import takes any names; one that takes none loads its module
+ * for what that does globally, as a side-effect import does.
+ * @param {any} ts
+ * @param {any} statement
+ */
+function importsNames(ts, statement) {
+ const clause = statement.importClause;
+ const bound = clause?.namedBindings;
+ return (
+ !!clause &&
+ (!!clause.name ||
+ (!!bound && (!ts.isNamedImports(bound) || bound.elements.length > 0)))
+ );
+}
+
+/**
+ * Whether a node gives type arguments to a value, not a type name: the base
+ * a class extends, or an instantiation expression (`select<string>`).
+ * @param {any} ts
+ * @param {any} node
+ */
+function isValueWithTypeArguments(ts, node) {
+ if (!ts.isExpressionWithTypeArguments(node)) return false;
+ const clause = node.parent;
+ if (!ts.isHeritageClause(clause)) return true;
+ return (
+ clause.token === ts.SyntaxKind.ExtendsKeyword &&
+ (ts.isClassDeclaration(clause.parent) ||
+ ts.isClassExpression(clause.parent))
+ );
+}
+
+/**
+ * Source text on one line, comments dropped, for a reason.
+ * @param {string} text
+ */
+function oneLine(text) {
+ return text
+ .replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, '')
+ .replace(/\s+/g, ' ')
+ .trim();
+}
+
+/**
+ * Whether a node reads a value: a property or element access, a call, or a
+ * name spread, assigned, passed or returned. A name that only declares or
+ * imports something is not read here, and may stand for a type.
+ * @param {any} ts
+ * @param {any} node
+ */
+function readsValue(ts, node) {
+ if (
+ ts.isPropertyAccessExpression(node) ||
+ ts.isElementAccessExpression(node) ||
+ ts.isCallExpression(node)
+ ) {
+ return true;
+ }
+ if (!ts.isIdentifier(node)) return false;
+ const parent = node.parent;
+ return (
+ ts.isSpreadAssignment(parent) ||
+ ts.isSpreadElement(parent) ||
+ ts.isJsxSpreadAttribute(parent) ||
+ ts.isShorthandPropertyAssignment(parent) ||
+ ((ts.isVariableDeclaration(parent) || ts.isPropertyAssignment(parent)) &&
+ parent.initializer === node) ||
+ (ts.isCallExpression(parent) && parent.arguments.includes(node)) ||
+ ts.isReturnStatement(parent) ||
+ ts.isArrayLiteralExpression(parent) ||
+ ts.isParenthesizedExpression(parent) ||
+ ts.isAsExpression(parent) ||
+ ts.isConditionalExpression(parent) ||
+ ts.isJsxExpression(parent) ||
+ ts.isExportAssignment(parent)
+ );
+}
+
+/**
+ * The name an access or call starts from: `fmt` in `fmt.parse(text)`.
+ * @param {any} ts
+ * @param {any} node
+ * @returns {string}
+ */
+function rootName(ts, node) {
+ let root = node;
+ while (
+ ts.isPropertyAccessExpression(root) ||
+ ts.isElementAccessExpression(root) ||
+ ts.isCallExpression(root)
+ ) {
+ root = root.expression;
+ }
+ return ts.isIdentifier(root) ? root.text : '';
+}
+
+/**
+ * Whether the compiler can only give a value its error type.
+ * @param {any} checker
+ * @param {any} node
+ */
+function isErrorValue(checker, node) {
+ try {
+ return checker.getTypeAtLocation(node).intrinsicName === 'error';
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Whether the compiler can only give a type node its error type.
+ * @param {any} checker
+ * @param {any} node
+ */
+function isErrorType(checker, node) {
+ try {
+ return checker.getTypeFromTypeNode(node).intrinsicName === 'error';
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * The first reference that does not resolve from the program's global roots,
+ * whose types every file sees: a type package the program loads by name
+ * (`compilerOptions.types`, `*` expanded as TypeScript does, or every
+ * package in `typeRoots` where TypeScript loads them all) that cannot be
+ * found, or a reference in a declaration file the package's own config
+ * includes, wherever it sits, or in the package's own type packages, or in a
+ * file they import. Of those, only a file that acts globally starts the walk:
+ * a script, `declare global`, `declare module`, `export as namespace`, an
+ * import that takes no names (a side-effect import, `import {} from`), a
+ * bare `export *`, or a `/// <reference>`. A config from above the package,
+ * such as a monorepo's root config, may include the whole repository, so
+ * only the package's own declaration files start the walk then. A
+ * dependency's declarations (below `node_modules`) are not followed: `tsc`
+ * skips their errors (`skipLibCheck`), and they reach a component only
+ * through the globals they declare.
+ * @param {any} ts the project's own `typescript`
+ * @param {any} program
+ * @param {any} checker
+ * @param {string[]} declarations the declaration files the config includes
+ * @param {any} options the program's compiler options
+ * @param {(file: string) => boolean} isOwnFile whether a file is the
+ * package's own
+ * @returns {UnresolvedReference | null}
+ */
+export function unresolvedGlobals(
+ ts,
+ program,
+ checker,
+ declarations,
+ options,
+ isOwnFile,
+) {
+ const config =
+ options.configFilePath ??
+ path.join(ts.sys.getCurrentDirectory(), 'tsconfig.json');
+ /** @type {(file: string) => boolean} */
+ const follow = file =>
+ isOwnFile(file) || !/[\\/]node_modules[\\/]/.test(file);
+ const own = isOwnFile(config);
+ // A declaration file reaches a component through what it does globally: a
+ // script, `declare global`, `declare module`, `export as namespace`, or an
+ // import that takes no names, a bare `export *` or a `/// <reference>`, made
+ // for what those load. A module that does none of these counts only where a
+ // component imports it.
+ /** @type {(sf: any) => boolean} */
+ const global = sf =>
+ sf &&
+ (!ts.isExternalModule(sf) ||
+ sf.referencedFiles.length > 0 ||
+ sf.typeReferenceDirectives.length > 0 ||
+ sf.statements.some(
+ (/** @type {any} */ statement) =>
+ (ts.isModuleDeclaration(statement) &&
+ (ts.isGlobalScopeAugmentation(statement) ||
+ ts.isStringLiteral(statement.name))) ||
+ ts.isNamespaceExportDeclaration(statement) ||
+ (ts.isImportDeclaration(statement) && !importsNames(ts, statement)) ||
+ (ts.isExportDeclaration(statement) &&
+ !!statement.moduleSpecifier &&
+ !statement.exportClause),
+ ));
+ const roots = declarations
+ .filter(file => own || isOwnFile(file))
+ .map(file => program.getSourceFile(file))
+ .filter(global);
+ // With `types` unset TypeScript 5 loads every package in `typeRoots`, and
+ // TypeScript 6 loads none; this asks the project's own which it loads.
+ for (const name of ts.getAutomaticTypeDirectiveNames(options, ts.sys)) {
+ const found = ts.resolveTypeReferenceDirective(
+ name,
+ path.join(path.dirname(config), '__inferred type names__.ts'),
+ options,
+ ts.sys,
+ ).resolvedTypeReferenceDirective?.resolvedFileName;
+ if (!found) {
+ return {name: `the types \`${name}\``, file: config, how: 'named'};
+ }
+ const sf = follow(found) && program.getSourceFile(found);
+ if (global(sf)) roots.push(sf);
+ }
+ return unresolvedReference(ts, program, checker, roots, follow, follow);
+}
diff --git a/packages/cli/foundation/discovery/unresolved-references.test.mjs b/packages/cli/foundation/discovery/unresolved-references.test.mjs
new file mode 100644
index 0000000000..ac11cd1596
--- /dev/null
+++ b/packages/cli/foundation/discovery/unresolved-references.test.mjs
@@ -0,0 +1,567 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file unresolvedReference() and unresolvedGlobals(): each kind of
+ * reference the compiler cannot resolve, how far the walk follows, and which
+ * declaration files and type packages start the global walk.
+ */
+
+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 {readPackageTsconfig} from './package-tsconfig.mjs';
+import {
+ unresolvedGlobals,
+ unresolvedReference,
+} from './unresolved-references.mjs';
+
+const require = createRequire(import.meta.url);
+const ts = require('typescript');
+
+/** @type {string} */
+let root;
+
+beforeEach(() => {
+ root = fs.realpathSync(
+ fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-unresolved-')),
+ );
+});
+
+afterEach(() => {
+ fs.rmSync(root, {recursive: true, force: true});
+});
+
+/**
+ * @param {string} rel
+ * @param {string | object} content
+ */
+function write(rel, content) {
+ const file = path.join(root, rel);
+ fs.mkdirSync(path.dirname(file), {recursive: true});
+ fs.writeFileSync(
+ file,
+ typeof content === 'string' ? content : JSON.stringify(content),
+ );
+ return file;
+}
+
+const OPTIONS = {
+ strict: true,
+ jsx: 'react-jsx',
+ module: 'esnext',
+ moduleResolution: 'bundler',
+ target: 'es2022',
+};
+
+/**
+ * A program over the given sources and the declaration files the package's
+ * config includes, as the props comparison builds it.
+ * @param {string} packageDir
+ * @param {string[]} sources
+ * @param {object} [extra] compiler options to add
+ */
+function load(packageDir, sources, extra = {}) {
+ const project = readPackageTsconfig(ts, packageDir, sources);
+ const options = {...project.options, ...extra};
+ const program = ts.createProgram({
+ rootNames: [...sources, ...project.declarations],
+ options,
+ });
+ /** @type {(file: string) => boolean} */
+ const isOwnFile = file => {
+ const rel = path.relative(packageDir, fs.realpathSync(file));
+ return (
+ !rel.startsWith('..') && !rel.split(path.sep).includes('node_modules')
+ );
+ };
+ return {
+ project,
+ options,
+ program,
+ checker: program.getTypeChecker(),
+ isOwnFile,
+ };
+}
+
+/** @param {string} dir */
+function dependency(dir, files) {
+ for (const [name, content] of Object.entries(files)) {
+ write(path.join(dir, name), content);
+ }
+}
+
+describe('unresolvedReference', () => {
+ it('finds the first reference that does not resolve, and follows only where told', () => {
+ write('tsconfig.json', {compilerOptions: OPTIONS});
+ write('src/theme.ts', 'export interface Theme { tone?: string }\n');
+ write('src/x.ts', 'export const fmt = 1;\n');
+ write(
+ 'src/defaults-src.ts',
+ 'declare const theme: {colors: {}};\nexport const defaults = {...theme.sizes};\n',
+ );
+ write(
+ 'src/x-values.ts',
+ 'export interface Theme { tone?: string }\nexport const fmt = (s: string) => s;\n',
+ );
+ dependency('node_modules/untyped-dep', {
+ 'package.json': {name: 'untyped-dep', main: 'index.js'},
+ 'index.js': 'export const fmt = text => text;\n',
+ });
+ dependency('node_modules/@acme/dep', {
+ 'package.json': {name: '@acme/dep', types: 'index.d.ts'},
+ 'index.d.ts':
+ "import type {Peer} from '@acme/not-installed-peer';\nexport type Dep = Peer;\n",
+ });
+ const cases = {
+ 'missing.ts':
+ "import type {X} from '@acme/not-installed';\nexport type Y = X;\n",
+ 'unnamed.ts':
+ "import type {Gone} from './theme';\nexport type Y = Gone;\n",
+ 'reexport.ts': "export {fmt, gone} from './x';\n",
+ 'types.ts': '/// <reference types="@acme/missing-types" />\nexport {};\n',
+ 'path.ts':
+ '/// <reference path="./generated/augment.d.ts" />\nexport {};\n',
+ 'effect.ts': "import '@acme/not-installed-effect';\nexport {};\n",
+ 'untyped.ts': "import {fmt} from 'untyped-dep';\nexport const y = fmt;\n",
+ 'jsx.tsx': 'export const A = () => <div />;\n',
+ 'dep.ts': "import type {Dep} from '@acme/dep';\nexport type Y = Dep;\n",
+ // Type names declared nowhere, which only `keyof`, a key or a query
+ // may reach; and names that resolve.
+ 'keyed.ts':
+ 'export type Y = Omit<{label: string; size?: number}, keyof NowhereProps>;\n',
+ 'template.ts':
+ 'export type Y = {[K in `on${NowhereKey}`]?: () => void};\n',
+ 'query.ts': 'export type Y = Parameters<typeof nowhereHook>[0];\n',
+ // A value declared nowhere behind a binding, a property that doesn't
+ // exist, and a name declared nowhere in a JavaScript file's JSDoc.
+ 'valued.ts':
+ 'const d = missingValue;\nexport type Y = Omit<{label: string; size?: number}, keyof typeof d>;\n',
+ 'indexed.ts':
+ "interface Theme { colors: {a: string} }\nexport type Y = Partial<Record<keyof Theme['sizes'], string>>;\n",
+ 'jsdoc.js':
+ '/** @param {Omit<{label: string; size?: number}, keyof NowhereJs>} props */\nexport function J(props) { return null; }\n',
+ // Tags whose types the compiler never reads.
+ 'jsdoctags.js':
+ '/**\n * @param {{label: string}} props\n * @throws {HttpError} when offline\n * @exception {NowhereError}\n * @see NowhereGuide\n * @see {@link NowhereLink}\n */\nexport function T(props) { return null; }\n',
+ // A class's base that names nothing, written or in `@augments`, and
+ // one that names a class.
+ 'baseless.ts':
+ 'export class X extends NowhereBase<{label?: string}> {}\n',
+ 'baselessjs.js':
+ 'class Real {}\n/** @augments {NowhereBase} */\nexport class X extends Real {}\n',
+ 'augments.js':
+ 'class Real {}\n/** @augments {Real} */\nexport class X extends Real {}\n',
+ // A class's base is a value, and a module found without types gives
+ // its names no types to resolve.
+ 'classbase.ts':
+ 'class Real<P> { props!: P }\nconst Base = Real;\nexport class X extends Base<{label?: string}> {}\nexport function mixin(B: typeof Real) { return class extends B {}; }\n',
+ // A value the compiler can't type, spread into an object, makes it
+ // `any`, so `keyof typeof` it takes any name.
+ 'spread.ts':
+ 'interface Theme { colors: {a: string} }\ndeclare const theme: Theme;\nconst defaults = {...theme.sizes};\nexport type Y = Omit<{label: string; size?: number}, keyof typeof defaults>;\n',
+ 'spreadname.ts':
+ 'const tones = {...undeclaredTones};\nexport type Y = Partial<Record<keyof typeof tones, string>>;\n',
+ // The same from another file of the package's, and a line that
+ // `@ts-expect-error` covers, which `tsc` accepts.
+ 'crossfile.ts':
+ "import {defaults} from './defaults-src';\nexport type Y = keyof typeof defaults;\n",
+ 'suppressed.ts':
+ 'declare const theme: {colors: {}};\nconst defaults = {\n // @ts-expect-error -- older themes have sizes\n ...theme.sizes,\n};\nexport type Y = keyof typeof defaults;\n',
+ // What an own function returns is read too.
+ 'called.ts':
+ 'function makeSlots() { return {...undeclaredSlots}; }\nconst slots = makeSlots();\nexport type Y = keyof typeof slots;\n',
+ // `tsc` reports no error in a `@ts-nocheck` file, or on a later line
+ // `@ts-expect-error` covers, or (without `noImplicitAny`) for an index
+ // that misses.
+ 'nocheck.ts':
+ '// @ts-nocheck\ndeclare const theme: {colors: {}};\nconst defaults = {...theme.sizes};\nexport type Y = keyof typeof defaults;\n',
+ 'laterline.ts':
+ 'declare const theme: {colors: {}};\nconst defaults = {\n ...theme\n // @ts-expect-error -- older themes have sizes\n .sizes,\n};\nexport type Y = keyof typeof defaults;\n',
+ 'indexmiss.ts':
+ "const COLORS = {red: '#f00'};\nfunction Base(props: {tone: string}) { const color = COLORS[props.tone]; return color; }\nexport type P = Parameters<typeof Base>[0];\n",
+ // A function passed to another, and a class field.
+ 'wrapped.ts':
+ 'function lazy<T>(make: () => T): T { return make(); }\nfunction makeSlots() { return {...undeclaredSlots}; }\nconst slots = lazy(makeSlots);\nexport type Y = keyof typeof slots;\n',
+ 'classfield.ts':
+ "class Store { slots = {...undeclaredSlots}; }\nexport type Y = keyof InstanceType<typeof Store>['slots'];\n",
+ // A written return type, overloads, and a call made for its effect
+ // decide nothing about the type, whatever the body holds.
+ 'declaredreturn.ts':
+ 'function makeSlots(): {a?: number} { const broken = undeclaredThing; return {}; }\nconst slots = makeSlots();\nexport type Y = keyof typeof slots;\n',
+ 'overloaded.ts':
+ 'function make(): {a?: number};\nfunction make(x?: number) { return {...undeclaredA}; }\nconst made = make();\nexport type Y = keyof typeof made;\n',
+ 'statement.ts':
+ 'function track() { undeclaredLogger.log(); }\nfunction Base(props: {tone?: string}) { track(); return null; }\nexport type P = Parameters<typeof Base>[0];\n',
+ // A class's instance type is inferred from its members too, wherever
+ // a type names the class.
+ 'classbyname.ts':
+ "class Store { slots = {...undeclaredSlots}; }\nexport type Y = keyof Store['slots'];\n",
+ 'classgetter.ts':
+ "class Store { get slots() { return {...undeclaredSlots}; } }\nexport type Y = keyof Store['slots'];\n",
+ 'extendscall.ts':
+ "function mixin() { return class { slots = {...undeclaredSlots}; }; }\nclass Store extends mixin() {}\nexport type Y = keyof Store['slots'];\n",
+ 'interfaceextends.ts':
+ "class Store { slots = {...undeclaredSlots}; }\ninterface Holder extends Store {}\nexport type Y = keyof Holder['slots'];\n",
+ // A class named only as a whole: its names are its written members
+ // and its base, so a broken member elsewhere in it decides nothing.
+ 'classmember.ts':
+ 'class Widget { state = {...undeclaredState}; }\nexport type P = {onReady?: (widget: Widget) => void};\n',
+ 'componentbase.ts':
+ "declare class Component<P> { props: P }\nclass Base<P> extends Component<P> { broken = {...undeclaredBroken}; }\nexport class AcmeX extends Base<{tone?: string}> {}\nexport type P = AcmeX['props'];\n",
+ // A base built by a call gives the class names of its own.
+ 'computedbase.ts':
+ 'function makeBase() { return undeclaredBase; }\nclass Store extends makeBase() {}\nexport type Y = keyof Store;\n',
+ // A cast that writes the type decides it; `as const` does not.
+ 'cast.ts':
+ 'const slots = {...undeclaredSlots} as {a?: number};\nexport type Y = keyof typeof slots;\n',
+ 'castconst.ts':
+ 'const slots = {...undeclaredSlots} as const;\nexport type Y = keyof typeof slots;\n',
+ // An instantiation expression takes type arguments for a value.
+ 'instantiation.ts':
+ 'function select<T>(value: T) { return value; }\nexport const selectString = select<string>;\nexport type S = typeof selectString;\n',
+ 'untypedq.ts':
+ "import {fmt} from 'untyped-dep';\nexport type F = typeof fmt;\nexport type G = typeof import('untyped-dep').fmt;\n",
+ // TypeScript reads no types from a `.ts` file's JSDoc.
+ 'tsdoc.ts':
+ '/** @param {NowhereDoc} x */\nexport function g(x: string) { return x; }\n',
+ // Values that resolve, and names that are not read as values.
+ 'values.ts':
+ "import {type Theme, fmt} from './x-values';\nconst base = {a: 1};\nexport const merged = {...base, b: [1].length, c: Math.max(1, 2), fmt};\nexport type V = Theme;\n",
+ 'known.ts':
+ "import type {Theme} from './theme';\nexport type Y<T> = {[K in keyof T]: Theme} & Partial<Record<'a', string>>;\nexport const sizes = ['sm', 'md'] as const;\nexport type W = Window & typeof globalThis;\nexport type G = keyof typeof globalThis;\nexport type U = typeof undefined;\nexport function f() { type A = typeof arguments; return 1; }\nexport type T = Theme['tone'];\n",
+ };
+ const sources = Object.entries(cases).map(([name, text]) =>
+ write(path.join('src', name), text),
+ );
+ const {program, checker, isOwnFile} = load(root, sources, {allowJs: true});
+ /** @type {(name: string, follow?: (file: string) => boolean, mine?: (file: string) => boolean) => string | undefined} */
+ const first = (name, follow = () => true, mine = isOwnFile) =>
+ unresolvedReference(
+ ts,
+ program,
+ checker,
+ [program.getSourceFile(path.join(root, 'src', name))],
+ follow,
+ mine,
+ )?.name;
+
+ expect(first('missing.ts')).toBe('`@acme/not-installed`');
+ expect(first('unnamed.ts')).toBe('`Gone` from `./theme`');
+ expect(first('reexport.ts')).toBe('`gone` from `./x`');
+ expect(first('types.ts')).toBe('the types `@acme/missing-types`');
+ expect(first('path.ts')).toBe('`./generated/augment.d.ts`');
+ // TypeScript 6 checks a side-effect import by default.
+ expect(first('effect.ts')).toBe('`@acme/not-installed-effect`');
+ // A module found without types resolves, and so does the JSX runtime
+ // import the compiler adds itself.
+ expect(first('untyped.ts')).toBeUndefined();
+ expect(first('jsx.tsx')).toBeUndefined();
+ // A dependency's own missing import, where the walk follows it; where it
+ // doesn't, the type that import leaves untyped in the package's own file.
+ expect(first('dep.ts')).toBe('`@acme/not-installed-peer`');
+ expect(first('dep.ts', isOwnFile)).toBe('`Dep`');
+ expect(first('keyed.ts')).toBe('`NowhereProps`');
+ expect(first('template.ts')).toBe('`NowhereKey`');
+ expect(first('query.ts')).toBe('`typeof nowhereHook`');
+ expect(first('valued.ts')).toBe('`typeof d`');
+ expect(first('indexed.ts')).toBe("`Theme['sizes']`");
+ expect(first('jsdoc.js')).toBe('`NowhereJs`');
+ expect(first('jsdoctags.js')).toBeUndefined();
+ expect(first('tsdoc.ts')).toBeUndefined();
+ expect(first('classbase.ts')).toBeUndefined();
+ expect(first('baseless.ts')).toBe('`NowhereBase`');
+ expect(first('baselessjs.js')).toBe('`NowhereBase`');
+ expect(first('augments.js')).toBeUndefined();
+ expect(first('untypedq.ts')).toBeUndefined();
+ expect(first('instantiation.ts')).toBeUndefined();
+ expect(first('spread.ts')).toBe('`theme.sizes`');
+ expect(first('spreadname.ts')).toBe('`undeclaredTones`');
+ expect(first('values.ts')).toBeUndefined();
+ expect(first('crossfile.ts')).toBe('`theme.sizes`');
+ expect(first('suppressed.ts')).toBeUndefined();
+ expect(first('called.ts')).toBe('`undeclaredSlots`');
+ expect(first('wrapped.ts')).toBe('`undeclaredSlots`');
+ expect(first('classfield.ts')).toBe('`undeclaredSlots`');
+ expect(first('declaredreturn.ts')).toBeUndefined();
+ expect(first('overloaded.ts')).toBeUndefined();
+ expect(first('statement.ts')).toBeUndefined();
+ for (const file of [
+ 'classbyname.ts',
+ 'classgetter.ts',
+ 'extendscall.ts',
+ 'interfaceextends.ts',
+ 'castconst.ts',
+ ]) {
+ expect.soft(first(file), file).toBe('`undeclaredSlots`');
+ }
+ expect(first('cast.ts')).toBeUndefined();
+ expect(first('computedbase.ts')).toBe('`undeclaredBase`');
+ expect.soft(first('classmember.ts'), 'classmember.ts').toBeUndefined();
+ expect.soft(first('componentbase.ts'), 'componentbase.ts').toBeUndefined();
+ expect(first('nocheck.ts')).toBeUndefined();
+ expect(first('laterline.ts')).toBeUndefined();
+ // With `noImplicitAny` the index miss is an error `tsc` reports.
+ expect(first('indexmiss.ts')).toBe('`COLORS[props.tone]`');
+ const loose = load(root, sources, {strict: false, noImplicitAny: false});
+ expect(
+ unresolvedReference(
+ ts,
+ loose.program,
+ loose.checker,
+ [loose.program.getSourceFile(path.join(root, 'src', 'indexmiss.ts'))],
+ () => true,
+ loose.isOwnFile,
+ ),
+ ).toBeNull();
+ expect(first('known.ts')).toBeUndefined();
+ // Only in the files the caller checks names in.
+ expect(
+ first(
+ 'keyed.ts',
+ () => true,
+ () => false,
+ ),
+ ).toBeUndefined();
+
+ const unchecked = load(root, sources, {
+ noUncheckedSideEffectImports: false,
+ });
+ expect(
+ unresolvedReference(
+ ts,
+ unchecked.program,
+ unchecked.checker,
+ [unchecked.program.getSourceFile(path.join(root, 'src', 'effect.ts'))],
+ () => true,
+ () => true,
+ ),
+ ).toBeNull();
+ });
+
+ it('gives each root the same answer, whatever an earlier call on the same program read', () => {
+ write('tsconfig.json', {compilerOptions: OPTIONS});
+ const header = write(
+ 'src/CardHeader.ts',
+ 'declare const theme: {colors: {}};\nexport const defaults = {...theme.sizes};\nexport type HeaderKeys = keyof typeof defaults;\n',
+ );
+ const card = write(
+ 'src/Card.ts',
+ "import {defaults} from './CardHeader';\nexport type CardKeys = keyof typeof defaults;\n",
+ );
+ for (const order of [
+ [card, header],
+ [header, card],
+ ]) {
+ const {program, checker, isOwnFile} = load(root, [card, header]);
+ const answers = order.map(
+ file =>
+ unresolvedReference(
+ ts,
+ program,
+ checker,
+ [program.getSourceFile(file)],
+ () => true,
+ isOwnFile,
+ )?.name,
+ );
+ expect(answers).toEqual(['`theme.sizes`', '`theme.sizes`']);
+ }
+ });
+});
+
+describe('unresolvedGlobals', () => {
+ it("starts from each declaration file the package's own config includes, wherever it sits, and from its own type packages", () => {
+ const widgets = path.join(root, 'packages', 'widgets');
+ const source = write(
+ 'packages/widgets/src/Badge.tsx',
+ 'export function Badge(props: {label?: string}) { return null; }\n',
+ );
+ dependency('packages/widgets/node_modules/@types/dep-globals', {
+ 'package.json': {name: '@types/dep-globals', types: 'index.d.ts'},
+ 'index.d.ts':
+ '/// <reference types="@acme/not-installed-runner" />\ndeclare var depGlobal: string;\n',
+ });
+ /** @type {(config: object) => import('./unresolved-references.mjs').UnresolvedReference | null} */
+ const globals = config => {
+ write('packages/widgets/tsconfig.json', config);
+ const {project, options, program, checker, isOwnFile} = load(widgets, [
+ source,
+ ]);
+ return unresolvedGlobals(
+ ts,
+ program,
+ checker,
+ project.declarations,
+ options,
+ isOwnFile,
+ );
+ };
+
+ // A declaration file outside the package that its own config includes.
+ write(
+ 'shared/globals.d.ts',
+ '/// <reference types="@acme/not-installed-css" />\ndeclare var shared: string;\n',
+ );
+ expect(
+ globals({compilerOptions: OPTIONS, include: ['src', '../../shared']}),
+ ).toMatchObject({name: 'the types `@acme/not-installed-css`'});
+
+ // The package's own type package, named in `types`.
+ write(
+ 'packages/widgets/types/css-prop/index.d.ts',
+ '/// <reference types="@acme/not-installed-css" />\ndeclare var cssProp: string;\n',
+ );
+ const typeRoots = ['./types', './node_modules/@types'];
+ expect(
+ globals({
+ compilerOptions: {...OPTIONS, typeRoots, types: ['css-prop']},
+ include: ['src'],
+ }),
+ ).toMatchObject({name: 'the types `@acme/not-installed-css`'});
+ // With `types` unset TypeScript 5 loads every package in `typeRoots`, as
+ // TypeScript 6 does for `types: ['*']`, so they are walked then too.
+ const ts5 = new Proxy(ts, {
+ get: (target, key) =>
+ key === 'getAutomaticTypeDirectiveNames'
+ ? (/** @type {any} */ options, /** @type {any} */ host) =>
+ target.getAutomaticTypeDirectiveNames(
+ {...options, types: options.types ?? ['*']},
+ host,
+ )
+ : target[key],
+ });
+ write('packages/widgets/tsconfig.json', {
+ compilerOptions: {...OPTIONS, typeRoots},
+ include: ['src'],
+ });
+ const five = load(widgets, [source], {types: ['*']});
+ expect(
+ unresolvedGlobals(
+ ts5,
+ five.program,
+ five.checker,
+ five.project.declarations,
+ {...five.options, types: undefined},
+ five.isOwnFile,
+ ),
+ ).toMatchObject({name: 'the types `@acme/not-installed-css`'});
+
+ // A module declaration file no component imports declares no globals,
+ // so a package only it imports is not followed; one that augments a
+ // module, or imports one for its effects, is.
+ write(
+ 'packages/widgets/src/api.d.ts',
+ "import type {Client} from '@acme/not-installed-client';\nexport type Api = Client;\n",
+ );
+ expect(globals({compilerOptions: OPTIONS, include: ['src']})).toBeNull();
+ write(
+ 'packages/widgets/src/api.d.ts',
+ "import type {Client} from '@acme/not-installed-client';\ndeclare module '@acme/ui' { interface Theme { client?: Client } }\nexport {};\n",
+ );
+ expect(globals({compilerOptions: OPTIONS, include: ['src']})).toMatchObject(
+ {name: '`@acme/not-installed-client`'},
+ );
+ for (const loads of [
+ "import '@acme/not-installed-css-prop';",
+ "import {} from '@acme/not-installed-css-prop';",
+ "import type {} from '@acme/not-installed-css-prop';",
+ "export * from '@acme/not-installed-css-prop';",
+ ]) {
+ write('packages/widgets/src/api.d.ts', `${loads}\nexport {};\n`);
+ expect(
+ globals({compilerOptions: OPTIONS, include: ['src']}),
+ ).toMatchObject({name: '`@acme/not-installed-css-prop`'});
+ }
+ // `export * as` binds the module's names under one, as `import * as`
+ // does, so it doesn't act globally.
+ for (const binds of [
+ "import * as legacy from '@acme/removed-package';",
+ "export * as legacy from '@acme/removed-package';",
+ ]) {
+ write('packages/widgets/src/api.d.ts', `${binds}\nexport {};\n`);
+ expect(globals({compilerOptions: OPTIONS, include: ['src']})).toBeNull();
+ }
+
+ // A UMD declaration file declares a global namespace for its module.
+ write(
+ 'packages/widgets/src/api.d.ts',
+ "import type {Theme} from '@acme/not-installed-theme';\nexport interface Props { theme?: Theme }\nexport as namespace AcmeLib;\n",
+ );
+ expect(globals({compilerOptions: OPTIONS, include: ['src']})).toMatchObject(
+ {name: '`@acme/not-installed-theme`'},
+ );
+ fs.rmSync(path.join(widgets, 'src', 'api.d.ts'));
+
+ // A type name declared nowhere, in the package's own declaration file.
+ write(
+ 'packages/widgets/src/names.d.ts',
+ 'type AcmeOmitted = Omit<{label: string}, keyof NowhereProps>;\n',
+ );
+ expect(globals({compilerOptions: OPTIONS, include: ['src']})).toMatchObject(
+ {name: '`NowhereProps`', how: 'used'},
+ );
+ fs.rmSync(path.join(widgets, 'src', 'names.d.ts'));
+
+ // A type package the config names that cannot be found.
+ expect(
+ globals({
+ compilerOptions: {...OPTIONS, types: ['@acme/not-installed-globals']},
+ include: ['src'],
+ }),
+ ).toEqual({
+ name: 'the types `@acme/not-installed-globals`',
+ file: path.join(widgets, 'tsconfig.json'),
+ how: 'named',
+ });
+
+ // A dependency's type package is not followed, named, under `*`, or
+ // referenced from the package's own declaration file.
+ for (const types of [['dep-globals'], ['*']]) {
+ expect(
+ globals({compilerOptions: {...OPTIONS, types}, include: ['src']}),
+ ).toBeNull();
+ }
+ write(
+ 'packages/widgets/src/env.d.ts',
+ '/// <reference types="dep-globals" />\ndeclare var env: string;\n',
+ );
+ expect(globals({compilerOptions: OPTIONS, include: ['src']})).toBeNull();
+ });
+
+ it("starts only from the package's own declaration files for a config from above it", () => {
+ // A monorepo's root config includes every file in the repository.
+ write('tsconfig.json', {compilerOptions: OPTIONS});
+ write(
+ 'types/global.d.ts',
+ "import type {Props} from '@acme/not-installed';\ndeclare global { type RepoProps = Props; }\n",
+ );
+ const widgets = path.join(root, 'packages', 'widgets');
+ const source = write(
+ 'packages/widgets/src/Badge.tsx',
+ 'export function Badge(props: {label?: string}) { return null; }\n',
+ );
+ const read = () => {
+ const {project, options, program, checker, isOwnFile} = load(widgets, [
+ source,
+ ]);
+ return unresolvedGlobals(
+ ts,
+ program,
+ checker,
+ project.declarations,
+ options,
+ isOwnFile,
+ );
+ };
+
+ expect(read()).toBeNull();
+
+ write(
+ 'packages/widgets/src/env.d.ts',
+ "import type {Env} from '@acme/not-installed-env';\ndeclare global { type WidgetEnv = Env; }\n",
+ );
+ expect(read()).toMatchObject({name: '`@acme/not-installed-env`'});
+ });
+});
diff --git a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
index 1033dad299..92ccca7370 100644
--- a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
+++ b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
@@ -254,6 +254,10 @@ const RUNNERS = {
runs: 'a contributed topic, for its catalog fields: name, title, description, category, and relationships',
sites: ['importDocModule'],
},
+ 'foundation/discovery/project-typescript.mjs': {
+ runs: "the project's own typescript, for the author checks that read source and docs with it, and its package.json for the version of one they cannot use",
+ sites: ['require(typescript)', 'require(typescript/package.json)'],
+ },
'foundation/discovery/template-adapter.mjs': {
runs: '@babel/parser, to find the fixture references and page-local bindings in template source; and a template doc that does not validate, to read the replacement it declares',
sites: ['importDocModule', 'require(@babel/parser)'],