Skip to content

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

TypeScript

feat(cli): integration check lists imported names a module does not export, and templates with no default export (#7786)

Joey1391928cf7df
diff --git a/.changeset/cli-integration-import-names.md b/.changeset/cli-integration-import-names.md
new file mode 100644
index 0000000000..2c36657edc
--- /dev/null
+++ b/.changeset/cli-integration-import-names.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] `astryx doctor integration validate` now also lists, from source and without a build, an import that names something its module does not export, as notes on its result (`data.notes`, each with its fix in the message). The notes are listed only: neither `doctor integration validate` nor `astryx integration check --strict` counts them or fails on them in 0.7.3, and they become failing warnings in the next minor release, so fix them now. It notes a component's import (the doc's `import`, or the one the CLI derives when the doc has none) that leads to a module that does not export the component, naming the subpath that does or the `exports` entry to add; a component example or a template that imports a name the package does not export; and a template source with no default export (`astryx template` still copies it, but its public import and anything that renders it get nothing), suggesting an exported PascalCase function, class or `const` (never a hook such as `useAccount`, a helper such as `formatBalance`, an ALL-CAPS constant or a type; with none, the fix stays generic). A name is judged only when a file the `exports` entry names is there to read in full: `export *` is followed, cycles included; a built module's declaration file (`x.d.ts` beside `x.js`, and the `.d.ts` files a declaration file's `export *` names) is read for the types it exports; and `export import Alias = Inner.Value` counts as an export. TypeScript source resolves a `./x.js` specifier to `./x.ts`, and a declaration file that is a module exports every top-level declaration unless it has an export list, `export *`, `export =` or a default export of an expression, as TypeScript does. Whatever the reader does not fully model is listed under `unchecked` in the `publicImports` report instead of as a note: a file the `exports` entry names that does not exist yet, a module whose list cannot be read in full (CommonJS, `export *` from another package), a declaration file with no import or export (a global script), every name it would report (other than a component doc's own component, which is always judged) while a TypeScript file in the package (outside `node_modules`) has a parsed `declare module` block for a relative path or the package's own name or a subpath of it, since such an augmentation can add names to that module (the reason names that file; `declare global`, a wildcard spec such as `'*.css'`, another package's name and a `declare module` in a comment do not count, and a file with `declare module` in its text that cannot be parsed counts), or a name missing from a JavaScript module with no declaration file, which may be a type.
+
+@josephfarina
diff --git a/.changeset/cli-integration-public-imports.md b/.changeset/cli-integration-public-imports.md
index dab20c8979..962c278476 100644
--- a/.changeset/cli-integration-public-imports.md
+++ b/.changeset/cli-integration-public-imports.md
@@ -2,6 +2,6 @@
'@astryxdesign/cli': patch
---
-[feat] `astryx doctor integration validate` now lists, from source and without a build, what an integration package tells apps to import that they cannot import, as notes on its result (`data.notes`, each with its fix in the message), the way it lists an ignored `cliCommand`. The notes are listed only: neither `doctor integration validate` nor `astryx integration check --strict` counts them or fails on them in 0.7.3, and they become failing warnings in the next minor release, so fix them now. It lists a component's import (the doc's `import`, or the one the CLI derives when the doc has none) or a template's public import whose subpath package.json `exports` does not declare (a missing key, a key whose only conditions an ES module import does not load, such as `require` or `types`, an `exports` that is a single string, a wildcard that does not match; an empty `exports` map declares nothing) or that names another package; a component example that imports a subpath the package does not declare; and a template that imports a relative path outside the templates root, or a path its own package or Core does not export. Each note names the fix, such as the exact `exports` entry to add. Only the declared subpath is judged, never the target file or the names it exports, so `exports` may point at build output that does not exist yet; wildcards and condition objects with `import` or `default` pass, an import of a subpath whose `exports` entry has only `types` targets is never judged as a run-time import (it passes when it is `import type`, when every binding is an inline `type`, or when every name it imports is one the `types` file declares as a type, and is listed under `unchecked` otherwise), a subpath an ES module import reaches only through `types` (such as `types` beside `require`) is judged the same way, and a `types` target under `require` does not count, and a package with no `exports` keeps its deep paths to files it ships. What it cannot judge (in a package with no `exports`, a deep path into build output not built yet, such as `dist/`; a template import of Core when `@astryxdesign/core` is not installed beside the package; every import of the package's own name when package.json has no `name`) is listed under `unchecked` in a new `publicImports` report on the result (`{status: 'checked', findings: [], unchecked: [{file, specifier, reason}]}`), which `integration check` counts as not compared.
+[feat] `astryx doctor integration validate` now lists, from source and without a build, what an integration package tells apps to import that they cannot import, as notes on its result (`data.notes`, each with its fix in the message), the way it lists an ignored `cliCommand`. The notes are listed only: neither `doctor integration validate` nor `astryx integration check --strict` counts them or fails on them in 0.7.3, and they become failing warnings in the next minor release, so fix them now. It lists a component's import (the doc's `import`, or the one the CLI derives when the doc has none) or a template's public import whose subpath package.json `exports` does not declare (a missing key, a key whose only conditions an ES module import does not load, such as `require` or `types`, an `exports` that is a single string, a wildcard that does not match; an empty `exports` map declares nothing) or that names another package; a component example that imports a subpath the package does not declare; and a template that imports a relative path outside the templates root, or a path its own package or Core does not export. Each note names the fix, such as the exact `exports` entry to add. A subpath is judged from its `exports` declaration alone, never by its target file, so `exports` may point at build output that does not exist yet; whether the module there exports the names an import asks for is noted too, also listed only in 0.7.3, when a target file is there to read in full (see the import-names note). Wildcards and condition objects with `import` or `default` pass, an import of a subpath whose `exports` entry has only `types` targets is never judged as a run-time import (it passes when it is `import type`, when every binding is an inline `type`, or when every name it imports is one the `types` file declares as a type, and is listed under `unchecked` otherwise), a subpath an ES module import reaches only through `types` (such as `types` beside `require`) is judged the same way, and a `types` target under `require` does not count, and a package with no `exports` keeps its deep paths to files it ships. What it cannot judge (in a package with no `exports`, a deep path into build output not built yet, such as `dist/`; a template import of Core when `@astryxdesign/core` is not installed beside the package; every import of the package's own name when package.json has no `name`) is listed under `unchecked` in a new `publicImports` report on the result (`{status: 'checked', findings: [], unchecked: [{file, specifier, reason}]}`), which `integration check` counts as not compared.
@josephfarina
diff --git a/packages/cli/api/integration/validate-integration-gaps.test.mjs b/packages/cli/api/integration/validate-integration-gaps.test.mjs
index b649c106ac..467dc8f246 100644
--- a/packages/cli/api/integration/validate-integration-gaps.test.mjs
+++ b/packages/cli/api/integration/validate-integration-gaps.test.mjs
@@ -580,6 +580,9 @@ describe('block component names', () => {
),
'templates/account-card.tsx':
"import {Helper} from 'some-lib';\nexport default function A() {\n return <Helper />;\n}\n",
+ // The package root the doc's derived import names exports the component.
+ 'index.tsx':
+ "export function Panel() { return null; }\nexport {AcmeWidget} from './components/AcmeWidget';\n",
});
expect(await allOf(dir)).toEqual([]);
diff --git a/packages/cli/api/integration/validateIntegration.doc.mjs b/packages/cli/api/integration/validateIntegration.doc.mjs
index f90babc30a..d03876794b 100644
--- a/packages/cli/api/integration/validateIntegration.doc.mjs
+++ b/packages/cli/api/integration/validateIntegration.doc.mjs
@@ -62,7 +62,7 @@ export const doc = {
{
type: 'integration.validate',
description:
- 'The result envelope: `data.validated`, false when nothing was validated — with no `package.json` at all, `data.issues` carries one `no_package` error-severity issue so the command exits 1; with a `package.json` but no integration manifest, `data.issues` is empty, which means "not looked at", not "healthy"; `data.name` and `data.version` of the validated package (both null when `data.validated` is false; `data.name` is `(local package)` when the local package.json has no readable name), plus `data.issues`, an AstryxIntegrationIssue[] of {code, severity: `warning` | `error`, message, fix?, file?, line?}: `fix` is the change that resolves the issue, and `file` and `line` where it is, relative to the package, when the check knows them; and `data.notes` when there are any: {code, message} information that fails nothing, such as `invalid_cli_command` for a `cliCommand` that was ignored as malformed and `cli_peer_version` when the running CLI is outside the `@astryxdesign/cli` peer range of the package, and the package layout findings added after the last minor release, each with its fix in the message: `duplicate_component_doc`, `symlinked_root`, `unreadable_file`, `invalid_package_json` (no `name` or `version`), `no_provider_id`, and `source_without_component_doc` for a doc whose file name differs from its source only in letter case where the two still pair; and `doc_name_mismatch` and `unknown_block_component` (see `docNames` and `blockComponents`); they become warnings in the next minor release. A `runner_command` note lists each Astryx command a topic writes with a package runner, with its file, line and the bare command to write. When the manifest loads, `data.docTypes` holds the doc type check: `status` (`checked` | `skipped`), `reason` when skipped, `typescript`, `docs` (doc values checked), `findings` ({doc, line, export, type, field, problem: `unknown_field` | `missing_field` | `wrong_type`, severity: `warning`, message, fix}), `unchecked` ({doc, reason}: a doc that could not be fully checked, or a root its reader cannot read), and `fixtures` when the components or docs root holds test fixture docs under `__tests__`: how many, none of them checked. When the manifest loads, `data.docNames` lists the component doc names it could not judge: `status` (`checked`), `findings` (always empty; a doc name the module its import names provably does not export is a `doc_name_mismatch` note, with its fix in the message) and `unchecked` ({file, name, reason}: a doc whose `name` differs from the name it is listed under and whose source exports cannot all be read, such as a re-export from another package). When the manifest loads, `data.blockComponents` lists the component names templates give in `exampleFor` or `componentsUsed` that could not be judged: `status` (`checked`), `findings` (always empty; a name neither the package nor Core has, and the template does not import, is an `unknown_block_component` note, with its fix in the message) and `unchecked` ({file, name, reason}: a name the template may reach through anything other than named imports and re-exports from Core, React, StyleX, local helpers or the entry of the package itself, such as an import from another package, a default or namespace import, an alias of or member read off an imported binding, require() or a dynamic import(), or a local module that cannot be read, or any name Core would have to resolve when Core is not installed). Since 0.7.3 each import apps cannot use is a note in `data.notes`, its fix inside the message, listed only: it does not fail this command or `integration check --strict`, and fails `--strict` from the next minor release. The codes are `component_import_not_exported`, `component_import_other_package`, `example_import_not_exported`, `template_import_not_exported`, `template_import_outside_root` and `template_private_import`. When the manifest loads, `data.publicImports` is `{status: \'checked\', findings: [], unchecked}`: `unchecked` lists each import the check could not judge, as {file, specifier, reason}, the reason starting `example <label>:` for an import in a component example: a deep path into build output not built yet in a package with no `exports`; a template import of Core when `@astryxdesign/core` is not installed beside the package (a `packages/core` of the workspace under another name does not count); every import of the package\'s own name when package.json has no `name` or a `name` that is not a bare package name; one entry for the whole check when package.json cannot be read; and an import of a subpath whose `exports` entry has only a `types` target, unless it is `import type`, every binding is an inline `type`, or every name it imports is a type its types file declares: a value import of a name that file does not declare as a type, a namespace or side-effect import, or any import when the types file cannot be read (it may be build output). `integration check` counts the unchecked as not compared; they never fail it.',
+ "The result envelope: `data.validated`, false when nothing was validated — with no `package.json` at all, `data.issues` carries one `no_package` error-severity issue so the command exits 1; with a `package.json` but no integration manifest, `data.issues` is empty, which means \"not looked at\", not \"healthy\"; `data.name` and `data.version` of the validated package (both null when `data.validated` is false; `data.name` is `(local package)` when the local package.json has no readable name), plus `data.issues`, an AstryxIntegrationIssue[] of {code, severity: `warning` | `error`, message, fix?, file?, line?}: `fix` is the change that resolves the issue, and `file` and `line` where it is, relative to the package, when the check knows them; and `data.notes` when there are any: {code, message} information that fails nothing, such as `invalid_cli_command` for a `cliCommand` that was ignored as malformed and `cli_peer_version` when the running CLI is outside the `@astryxdesign/cli` peer range of the package, and the package layout findings added after the last minor release, each with its fix in the message: `duplicate_component_doc`, `symlinked_root`, `unreadable_file`, `invalid_package_json` (no `name` or `version`), `no_provider_id`, and `source_without_component_doc` for a doc whose file name differs from its source only in letter case where the two still pair; and `doc_name_mismatch` and `unknown_block_component` (see `docNames` and `blockComponents`); they become warnings in the next minor release. A `runner_command` note lists each Astryx command a topic writes with a package runner, with its file, line and the bare command to write. When the manifest loads, `data.docTypes` holds the doc type check: `status` (`checked` | `skipped`), `reason` when skipped, `typescript`, `docs` (doc values checked), `findings` ({doc, line, export, type, field, problem: `unknown_field` | `missing_field` | `wrong_type`, severity: `warning`, message, fix}), `unchecked` ({doc, reason}: a doc that could not be fully checked, or a root its reader cannot read), and `fixtures` when the components or docs root holds test fixture docs under `__tests__`: how many, none of them checked. When the manifest loads, `data.docNames` lists the component doc names it could not judge: `status` (`checked`), `findings` (always empty; a doc name the module its import names provably does not export is a `doc_name_mismatch` note, with its fix in the message) and `unchecked` ({file, name, reason}: a doc whose `name` differs from the name it is listed under and whose source exports cannot all be read, such as a re-export from another package). When the manifest loads, `data.blockComponents` lists the component names templates give in `exampleFor` or `componentsUsed` that could not be judged: `status` (`checked`), `findings` (always empty; a name neither the package nor Core has, and the template does not import, is an `unknown_block_component` note, with its fix in the message) and `unchecked` ({file, name, reason}: a name the template may reach through anything other than named imports and re-exports from Core, React, StyleX, local helpers or the entry of the package itself, such as an import from another package, a default or namespace import, an alias of or member read off an imported binding, require() or a dynamic import(), or a local module that cannot be read, or any name Core would have to resolve when Core is not installed). Since 0.7.3 each import apps cannot use is a note in `data.notes`, its fix inside the message, listed only: it does not fail this command or `integration check --strict`, and fails `--strict` from the next minor release. The codes are `component_import_not_exported`, `component_import_other_package`, `component_import_missing_name`, `example_import_not_exported`, `example_import_missing_name`, `template_import_not_exported`, `template_import_outside_root`, `template_private_import`, `template_import_missing_name` and `template_no_default_export`. When the manifest loads, `data.publicImports` is `{status: 'checked', findings: [], unchecked}`: `unchecked` lists each import the check could not judge, as {file, specifier, reason}, the reason starting `example <label>:` for an import in a component example: an `exports` target not built yet; a module whose export list cannot be read in full (CommonJS, or a declaration file it cannot read); a root import in a package with no `exports` (the root module `main` names is not read); every name an import (other than a component doc's own component) names that its module does not export, while a TypeScript file in the package has a `declare module` block for a relative path or the package's own name or a subpath of it, which can add names to that module (a `declare module` in a comment, `declare global`, a wildcard such as `'*.css'`, and another package's name do not count; a file whose text has `declare module` but that cannot be parsed counts); the same for every such name when the package has more than 5,000 files to search for that block; a deep path into build output not built yet in a package with no `exports`; a template import of Core when `@astryxdesign/core` is not installed beside the package (a `packages/core` of the workspace under another name does not count); every import of the package's own name when package.json has no `name` or a `name` that is not a bare package name; one entry for the whole check when package.json cannot be read; and an import of a subpath whose `exports` entry has only a `types` target, unless it is `import type`, every binding is an inline `type`, or every name it imports is a type its types file declares: a value import of a name that file does not declare as a type, a namespace or side-effect import, or any import when the types file cannot be read (it may be build output). `integration check` counts the unchecked as not compared; they never fail it.",
},
],
examples: [
diff --git a/packages/cli/assets/docs/tree/checks.doc.mjs b/packages/cli/assets/docs/tree/checks.doc.mjs
index 9ff807996e..0e5d4045ff 100644
--- a/packages/cli/assets/docs/tree/checks.doc.mjs
+++ b/packages/cli/assets/docs/tree/checks.doc.mjs
@@ -32,7 +32,7 @@ export const docs = {
'`astryx doctor integration validate`',
'The manifest loads, each root holds contributions the CLI can read, and each doc matches its authoring type. Notes, which fail nothing, list a malformed `cliCommand` and each command a topic writes with a package runner (`runner_command`)',
'A declared root is missing (`missing_root`), a contribution does not load (`invalid_doc`, `invalid_component`, `invalid_theme`), or two templates in the package replace one Core id (`ambiguous_template_replacement`)',
- "The manifest has a key this CLI does not know (`unknown_manifest_key`), or a doc field does not match the doc's authoring type: a field the type does not have, a missing required field, or a value outside the field's type. It also warns on what no reader can serve: a prop listed twice (`duplicate_prop`), a `propDescriptions` key that names no documented prop (`unknown_translated_prop`), a section with no content (`empty_section`), two sections of a topic with one key (`duplicate_section_key`), or a `.doc.zh.mjs` or `.doc.dense.mjs` overlay beside no topic file (`orphan_doc_overlay`). Since 0.7.3 it also lists, from source and without failing, what the package tells apps to import that they cannot: a component's import (the doc's `import`, or the one the CLI derives) or a template's public import whose subpath package.json `exports` does not declare (`component_import_not_exported`, `template_import_not_exported`) or that names another package (`component_import_other_package`); an example that imports an undeclared subpath (`example_import_not_exported`); a template that imports a path outside the templates root (`template_import_outside_root`) or a path its package or Core does not export (`template_private_import`). Each is a note, printed with its fix, that fails `--strict` from the next minor; an import it cannot judge, such as a deep path into a `dist/` not built yet, is listed under `publicImports` as not checked. It checks docs with your installed `typescript`, or, where that is missing or has no JavaScript compiler API (TypeScript 7), with an installed `@typescript/typescript6`; without either, it prints `[skip] Docs not type-checked`. With no `astryx.integration.mjs` it prints a hint and exits 0",
+ "The manifest has a key this CLI does not know (`unknown_manifest_key`), or a doc field does not match the doc's authoring type: a field the type does not have, a missing required field, or a value outside the field's type. It also warns on what no reader can serve: a prop listed twice (`duplicate_prop`), a `propDescriptions` key that names no documented prop (`unknown_translated_prop`), a section with no content (`empty_section`), two sections of a topic with one key (`duplicate_section_key`), or a `.doc.zh.mjs` or `.doc.dense.mjs` overlay beside no topic file (`orphan_doc_overlay`). Since 0.7.3 it also lists, from source and without failing, what the package tells apps to import that they cannot: a component's import (the doc's `import`, or the one the CLI derives) or a template's public import whose subpath package.json `exports` does not declare (`component_import_not_exported`, `template_import_not_exported`) or that names another package (`component_import_other_package`); an example that imports an undeclared subpath (`example_import_not_exported`); a template that imports a path outside the templates root (`template_import_outside_root`) or a path its package or Core does not export (`template_private_import`). It lists the same way a component's import whose module does not export the component (`component_import_missing_name`), an example or a template that imports a name its package does not export (`example_import_missing_name`, `template_import_missing_name`), and a template source with no default export (`template_no_default_export`). Each is a note, printed with its fix, that fails `--strict` from the next minor; an import it cannot judge, such as an `exports` target not built yet or a deep path into a `dist/` not built yet, is listed under `publicImports` as not checked. It checks docs with your installed `typescript`, or, where that is missing or has no JavaScript compiler API (TypeScript 7), with an installed `@typescript/typescript6`; without either, it prints `[skip] Docs not type-checked`. With no `astryx.integration.mjs` it prints a hint and exits 0",
],
[
'`astryx doctor integration components`',
diff --git a/packages/cli/foundation/integrations/public-imports.mjs b/packages/cli/foundation/integrations/public-imports.mjs
index bd9b6413e8..8d0a53eacc 100644
--- a/packages/cli/foundation/integrations/public-imports.mjs
+++ b/packages/cli/foundation/integrations/public-imports.mjs
@@ -6,21 +6,26 @@
*
* @input A package directory and its loaded integration record.
* @output Notes, listed on validate's result and never counted (they fail
- * `--strict` from the next minor), for: a component's import (the doc's `import`, or the one
- * the CLI derives) or a template's public import whose subpath
- * package.json `exports` does not declare (or that names another package);
- * a component example that imports an undeclared subpath; a template
- * source that imports a relative path outside the templates root, or an
- * undeclared subpath of its own package or of Core. Imports it cannot
- * judge (Core not installed) are listed in a report.
+ * `--strict` from the next minor), for: a component's import (the doc's
+ * `import`, or the one the CLI derives) or a template's public import whose
+ * subpath package.json `exports` does not declare (or that names another
+ * package), or whose module does not export the component; a component
+ * example that imports an undeclared subpath or a name its package does not
+ * export; a template source with no default export, or one that imports a
+ * relative path outside the templates root, an undeclared subpath of its own
+ * package or of Core, or a name its package does not export. Imports it
+ * cannot judge are listed in a report.
* @position foundation/integrations, beside the other on-disk contribution
* validators; run by `astryx doctor integration validate` (and so by
* `integration check`) through api/integration/validate-integration.mjs.
*
* An `exports` target may point at build output that does not exist yet, so
- * only the declared subpath is judged here, never the target file or the
- * names it exports; `integration verify` resolves those from the packed
- * package.
+ * only the declared subpath is judged here, never the target file. A name is
+ * judged only when a declared target exists on disk and its export list can be
+ * read completely, and (for a name other than a doc's component) no
+ * TypeScript file in the package has a `declare module` block for one of its
+ * own modules (which can add names to it); anything less is left to
+ * `integration verify`.
*/
import * as fs from 'node:fs';
@@ -115,15 +120,23 @@ const PARSE_PLUGINS = /** @type {any} */ ([
'exportDefaultFrom',
]);
-/** @param {string} text */
-function parseModuleText(text) {
+/** The plugins without `jsx`: `.ts` files allow `<T>value` assertions. */
+const TS_PARSE_PLUGINS = PARSE_PLUGINS.filter(
+ (/** @type {unknown} */ plugin) => plugin !== 'jsx',
+);
+
+/**
+ * @param {string} text
+ * @param {{jsx?: boolean}} [options] `jsx: false` parses TypeScript only
+ */
+function parseModuleText(text, {jsx = true} = {}) {
return parse(text, {
sourceType: 'module',
allowImportExportEverywhere: true,
allowReturnOutsideFunction: true,
allowAwaitOutsideFunction: true,
errorRecovery: true,
- plugins: PARSE_PLUGINS,
+ plugins: jsx ? PARSE_PLUGINS : TS_PARSE_PLUGINS,
});
}
@@ -215,6 +228,27 @@ export function readImports(text) {
/** @typedef {import('./exports-subpaths.mjs').SubpathDeclaration} SubpathDeclaration */
+/**
+ * The files on disk a declared subpath can load, in condition order of the
+ * package.json (any condition); empty when none exists yet (build output).
+ * @param {string} packageDir
+ * @param {SubpathDeclaration} declaration
+ * @returns {string[]}
+ */
+function existingTargets(packageDir, declaration) {
+ if (declaration.state !== 'declared') return [];
+ const root = path.resolve(packageDir);
+ return allTargets(declaration.value)
+ .filter(target => target.startsWith('./'))
+ .map(target =>
+ path.resolve(root, target.replaceAll('*', declaration.wildcard ?? '')),
+ )
+ .filter(
+ file =>
+ (file === root || file.startsWith(root + path.sep)) && isFile(file),
+ );
+}
+
/**
* How a package declares one subpath. A package with no `exports` keeps its
* legacy deep paths: a subpath that names a file on disk (with or without a
@@ -345,6 +379,534 @@ function exportsFix(exportsField, state, subpath, target) {
return `add ${entry} to package.json "exports" (or the built file it compiles to).`;
}
+// ── Module export names ─────────────────────────────────────────────
+
+/**
+ * Export lists read during one public-import check, by file. Scoped to that
+ * check, so a later check in the same process rereads every module.
+ * @typedef {Map<string, {names: Set<string>, complete: boolean, types: Set<string>, typed: boolean}>} ExportNameCache
+ */
+
+const DECLARATION_RE = /\.d\.[cm]?ts$/u;
+const DECLARATION_EXTENSIONS = ['.d.ts', '.d.mts', '.d.cts'];
+
+/**
+ * The declaration file beside a built module (`x.js` → `x.d.ts`), if any.
+ * @param {string} file
+ * @returns {string | null}
+ */
+function declarationTwin(file) {
+ const m = /\.([cm]?)jsx?$/u.exec(file);
+ if (!m) return null;
+ const stem = file.slice(0, m.index);
+ return (
+ [`.d.${m[1]}ts`, '.d.ts'].map(ext => `${stem}${ext}`).find(isFile) ?? null
+ );
+}
+
+/** @param {string} specifier @param {string} fromFile */
+function resolveRelative(specifier, fromFile) {
+ const base = path.resolve(path.dirname(fromFile), specifier);
+ const stripped = base.replace(/\.(?:m?js|jsx|cjs)$/u, '');
+ // TypeScript source resolves `./x.js` to `./x.ts` (or .tsx, .d.ts) first.
+ if (TYPED_RE.test(fromFile) && !DECLARATION_RE.test(fromFile)) {
+ const source = [
+ ...['.ts', '.tsx', '.mts', '.cts'].map(ext => `${stripped}${ext}`),
+ ...DECLARATION_EXTENSIONS.map(ext => `${stripped}${ext}`),
+ ].find(isFile);
+ if (source && stripped !== base) return source;
+ }
+ // A declaration file's `export * from './x.js'` names `./x.d.ts`.
+ if (DECLARATION_RE.test(fromFile)) {
+ const twin = [
+ ...DECLARATION_EXTENSIONS.map(ext => `${stripped}${ext}`),
+ ...DECLARATION_EXTENSIONS.map(ext => path.join(base, `index${ext}`)),
+ ].find(isFile);
+ if (twin) return twin;
+ }
+ const candidates = [
+ base,
+ ...MODULE_EXTENSIONS.map(ext => `${base}${ext}`),
+ ...MODULE_EXTENSIONS.map(ext => `${stripped}${ext}`),
+ ...MODULE_EXTENSIONS.map(ext => path.join(base, `index${ext}`)),
+ ];
+ return candidates.find(isFile) ?? null;
+}
+
+/**
+ * Every name (runtime or type) a module exports, and whether the list is
+ * complete: an `export *` from another package, `export =`, or a module that
+ * does not parse leaves it incomplete, and then no name is judged missing.
+ * @param {string} file
+ * @param {ExportNameCache} [cache] export lists already read in this check
+ * @returns {{names: Set<string>, complete: boolean, types: Set<string>, typed: boolean}}
+ * `types`: the names exported only as types (an interface, a type alias,
+ * `export type`); `typed`: the list includes every type the module
+ * exports (TypeScript source, or a JavaScript module whose declaration
+ * file was read in full), so a name absent from it is absent as a type too
+ */
+export function moduleExportNames(file, cache = new Map()) {
+ const {names, complete, types, typed} = readExportNames(file, cache, []);
+ return {names, complete, types, typed};
+}
+
+/** TypeScript source or a declaration file: its exports include its types. */
+const TYPED_RE = /\.(?:[cm]?tsx?)$/u;
+
+/**
+ * One module's export list, following local `export *` declarations. `stack`
+ * holds the modules whose lists are being read: an `export *` that reaches one
+ * of them closes a cycle, and a list read through a cycle the module does not
+ * close is not cached, since it lacks what the module on the stack exports.
+ * @param {string} file
+ * @param {ExportNameCache} cache
+ * @param {string[]} stack
+ * @returns {{names: Set<string>, complete: boolean, types: Set<string>, typed: boolean, cycleTo: Set<string>}}
+ */
+function readExportNames(file, cache, stack) {
+ if (stack.includes(file)) {
+ return {
+ names: new Set(),
+ complete: true,
+ types: new Set(),
+ typed: true,
+ cycleTo: new Set([file]),
+ };
+ }
+ const cached = cache.get(file);
+ if (cached) return {...cached, cycleTo: new Set()};
+ const own = readOwnExportNames(file, cache, stack);
+ const {names, types, cycleTo} = own;
+ let {complete, typed} = own;
+ // A JavaScript module's declaration file lists its types, at every level
+ // an `export *` reaches.
+ const twin = declarationTwin(file);
+ if (twin && !stack.includes(twin)) {
+ const declared = readExportNames(twin, cache, [...stack, file]);
+ for (const name of declared.names) names.add(name);
+ for (const name of declared.types) types.add(name);
+ for (const each of declared.cycleTo) cycleTo.add(each);
+ if (declared.complete && declared.typed) {
+ complete = true;
+ typed = true;
+ }
+ }
+ cycleTo.delete(file);
+ const value = {names, complete, types, typed};
+ if (cycleTo.size === 0) cache.set(file, value);
+ return {...value, cycleTo};
+}
+
+/**
+ * The exports one module itself declares, following local `export *` (each
+ * through {@link readExportNames}); its declaration file is merged by the
+ * caller.
+ * @param {string} file
+ * @param {ExportNameCache} cache
+ * @param {string[]} stack
+ * @returns {{names: Set<string>, complete: boolean, types: Set<string>, typed: boolean, cycleTo: Set<string>}}
+ */
+function readOwnExportNames(file, cache, stack) {
+ /** @type {Set<string>} */
+ const names = new Set();
+ /** @type {Set<string>} */
+ const types = new Set();
+ /** @type {Set<string>} */
+ const cycleTo = new Set();
+ let typed = TYPED_RE.test(file);
+ /** @param {boolean} complete */
+ const done = complete => ({names, complete, types, typed, cycleTo});
+ // A CommonJS module's exports cannot be read from declarations: leave it
+ // unjudged rather than read it as exporting nothing. That is any .cjs/.cts
+ // file, any file (built `dist/*.js` included) with no ES module import or
+ // export, and any file that also assigns `module.exports` or `exports.*`.
+ if (/\.c[jt]s$/u.test(file)) return done(false);
+ let complete = true;
+ let ast;
+ let text;
+ try {
+ text = fs.readFileSync(file, 'utf-8');
+ ast = parseModuleText(text);
+ if (ast.errors?.length) complete = false;
+ } catch {
+ return done(false);
+ }
+ const esm = ast.program.body.some(
+ (/** @type {any} */ node) =>
+ node.type === 'ImportDeclaration' ||
+ node.type === 'ExportNamedDeclaration' ||
+ node.type === 'ExportDefaultDeclaration' ||
+ node.type === 'ExportAllDeclaration' ||
+ node.type === 'TSExportAssignment',
+ );
+ // A declaration file with no import or export is a global script: no
+ // module import can read it (TypeScript: "is not a module"). Not judged.
+ if (!esm) return done(false);
+ if (/\b(?:module\.exports|exports\.[\w$]+)\s*=/u.test(text)) {
+ return done(false);
+ }
+ // A declaration file that is a module exports every top-level declaration,
+ // marked or not, unless it has an export list (`export {}`, `export {…}
+ // from`), `export *`, `export =`, or a default export of an expression
+ // (TypeScript's rule for ambient modules). A default-exported declaration
+ // (`export default function`, `class`, `interface`) does not end it.
+ if (DECLARATION_RE.test(file)) {
+ const implicit = !ast.program.body.some(
+ (/** @type {any} */ node) =>
+ (node.type === 'ExportNamedDeclaration' && !node.declaration) ||
+ (node.type === 'ExportDefaultDeclaration' &&
+ ![
+ 'FunctionDeclaration',
+ 'TSDeclareFunction',
+ 'ClassDeclaration',
+ 'TSInterfaceDeclaration',
+ ].includes(node.declaration?.type)) ||
+ node.type === 'TSExportAssignment' ||
+ node.type === 'ExportAllDeclaration',
+ );
+ if (implicit) {
+ for (const node of ast.program.body) {
+ const d = /** @type {any} */ (
+ node.type === 'ExportNamedDeclaration' ? node.declaration : node
+ );
+ if (!d) continue;
+ if (d.type === 'VariableDeclaration') {
+ for (const v of d.declarations ?? []) {
+ if (v.id?.type === 'Identifier') names.add(v.id.name);
+ else complete = false;
+ }
+ } else if (
+ d.type === 'TSInterfaceDeclaration' ||
+ d.type === 'TSTypeAliasDeclaration'
+ ) {
+ names.add(d.id.name);
+ types.add(d.id.name);
+ } else if (
+ [
+ 'FunctionDeclaration',
+ 'TSDeclareFunction',
+ 'ClassDeclaration',
+ 'TSEnumDeclaration',
+ 'TSModuleDeclaration',
+ ].includes(d.type) &&
+ d.id?.type === 'Identifier'
+ ) {
+ names.add(d.id.name);
+ }
+ }
+ }
+ }
+ for (const node of ast.program.body) {
+ if (node.type === 'ExportDefaultDeclaration') names.add('default');
+ else if (node.type === 'TSExportAssignment') complete = false;
+ else if (
+ node.type === 'TSImportEqualsDeclaration' &&
+ /** @type {any} */ (node).isExport
+ ) {
+ // `export import Alias = Inner.Value` exports Alias. Whether a
+ // type-only one names a value cannot be read, so the list is no longer
+ // complete.
+ names.add(/** @type {any} */ (node).id.name);
+ if (/** @type {any} */ (node).importKind === 'type') {
+ types.add(/** @type {any} */ (node).id.name);
+ complete = false;
+ }
+ } else if (node.type === 'ExportNamedDeclaration') {
+ const d = /** @type {any} */ (node.declaration);
+ const typeOnly = /** @type {any} */ (node).exportKind === 'type';
+ if (d) {
+ if (d.id?.name) {
+ names.add(d.id.name);
+ if (
+ typeOnly ||
+ d.type === 'TSInterfaceDeclaration' ||
+ d.type === 'TSTypeAliasDeclaration'
+ ) {
+ types.add(d.id.name);
+ }
+ }
+ for (const v of d.declarations ?? []) {
+ if (v.id?.type === 'Identifier') names.add(v.id.name);
+ else complete = false;
+ }
+ }
+ for (const sp of /** @type {any[]} */ (node.specifiers ?? [])) {
+ const exported = sp.exported?.name ?? sp.exported?.value;
+ if (!exported) continue;
+ names.add(exported);
+ if (typeOnly || sp.exportKind === 'type') types.add(exported);
+ }
+ } else if (node.type === 'ExportAllDeclaration') {
+ const n = /** @type {any} */ (node);
+ if (n.exported) {
+ names.add(n.exported.name ?? n.exported.value);
+ continue;
+ }
+ const source = String(n.source.value);
+ const target = source.startsWith('.')
+ ? resolveRelative(source, file)
+ : null;
+ if (!target) {
+ complete = false;
+ continue;
+ }
+ const inner = readExportNames(target, cache, [...stack, file]);
+ for (const name of inner.names) if (name !== 'default') names.add(name);
+ for (const name of inner.types) types.add(name);
+ if (!inner.complete) complete = false;
+ if (!inner.typed) typed = false;
+ for (const each of inner.cycleTo) cycleTo.add(each);
+ }
+ }
+ return done(complete);
+}
+
+/**
+ * Every file a declared subpath names, and whether each is on disk.
+ * @param {string} packageDir
+ * @param {SubpathDeclaration} declaration
+ * @returns {{files: string[], allPresent: boolean}}
+ */
+function declaredTargets(packageDir, declaration) {
+ if (declaration.state !== 'declared') return {files: [], allPresent: false};
+ const root = path.resolve(packageDir);
+ const all = allTargets(declaration.value)
+ .filter(target => target.startsWith('./'))
+ .map(target =>
+ path.resolve(root, target.replaceAll('*', declaration.wildcard ?? '')),
+ )
+ .filter(file => file === root || file.startsWith(root + path.sep));
+ const files = all.filter(isFile);
+ return {files, allPresent: files.length === all.length};
+}
+
+/**
+ * The names an import statement asks for that the module provably lacks.
+ * A name is missing only when every file the subpath names is on disk and
+ * read in full, and at least one of those lists includes its types: any
+ * construct the reader does not model leaves the import unchecked.
+ * @param {ImportStatement} statement
+ * @param {string[]} files candidate targets on disk
+ * @param {ExportNameCache} cache
+ * @param {boolean} [allPresent] every target the subpath names is on disk
+ * @param {boolean} [values] every name is known to be a value (a component),
+ * so a list without the module's types can still judge it
+ * @returns {string[] | null} null when it cannot be judged
+ */
+function missingNames(
+ statement,
+ files,
+ cache,
+ allPresent = true,
+ values = false,
+) {
+ // A type-only name may live only in a declaration file: not judged.
+ const wanted = statement.names
+ .filter(binding => !binding.typeOnly)
+ .map(binding => binding.imported);
+ if (wanted.length === 0) return [];
+ if (files.length === 0) return null;
+ // Any condition's file (source or built) that has every name settles it.
+ let incomplete = false;
+ let typed = false;
+ /** @type {Set<string>} */
+ const seen = new Set();
+ for (const file of files) {
+ const list = moduleExportNames(file, cache);
+ if (wanted.every(name => list.names.has(name))) return [];
+ if (!list.complete) incomplete = true;
+ if (list.typed) typed = true;
+ for (const name of list.names) seen.add(name);
+ }
+ // A target not built yet, a list cut short, or one without the module's
+ // types (a name written without `type` may be a type) is not judged.
+ if (incomplete || (!typed && !values) || !allPresent) return null;
+ return wanted.filter(name => !seen.has(name));
+}
+
+const AUGMENTATION_HINT_RE = /\bdeclare\s+module\b/u;
+const TYPESCRIPT_FILE_RE = /\.(?:d\.[cm]?ts|[cm]?ts|tsx)$/u;
+const AUGMENTATION_WALK_LIMIT = 5000;
+
+/**
+ * Whether a TypeScript file has a real `declare module '<spec>'` block for a
+ * module of this package: a relative spec, or the package's own name or a
+ * subpath of it. Comments, `declare global`, wildcard specs (`'*.css'`) and
+ * other packages' names do not count. A `.tsx` file is parsed with JSX, any
+ * other TypeScript file without it (so `<T>value` assertions parse); a file
+ * with `declare module` in its text that still fails to parse counts as
+ * augmenting.
+ * @param {Context} ctx
+ * @param {string} text
+ * @param {string} file
+ */
+function augmentsOwnModule(ctx, text, file) {
+ if (!AUGMENTATION_HINT_RE.test(text)) return false;
+ let body;
+ try {
+ body = parseModuleText(text, {jsx: file.endsWith('.tsx')}).program.body;
+ } catch {
+ return true;
+ }
+ return body.some(node => {
+ const d = node.type === 'ExportNamedDeclaration' ? node.declaration : node;
+ if (d?.type !== 'TSModuleDeclaration' || d.id?.type !== 'StringLiteral')
+ return false;
+ const spec = String(d.id.value);
+ if (spec.includes('*')) return false;
+ if (spec.startsWith('./') || spec.startsWith('../')) return true;
+ return (
+ ctx.name != null && (spec === ctx.name || spec.startsWith(`${ctx.name}/`))
+ );
+ });
+}
+
+/**
+ * The first TypeScript file in the package (outside `node_modules` and dot
+ * folders) with a `declare module '…'` block for a module of the package,
+ * read once per check. Such a block can add names to that module, so while
+ * one exists no name is judged missing: what TypeScript merges is not
+ * modelled. A package too large to walk counts as augmented.
+ * @param {Context} ctx
+ * @returns {string | null} the reason names were not checked, or null
+ */
+function augmentationReason(ctx) {
+ if (ctx.augmentation !== undefined) return ctx.augmentation;
+ const root = path.resolve(ctx.packageDir);
+ /** @type {string[]} */
+ const queue = [root];
+ let seen = 0;
+ /** @type {string | null} */
+ let reason = null;
+ walk: while (queue.length > 0) {
+ const current = /** @type {string} */ (queue.shift());
+ let entries;
+ try {
+ entries = fs.readdirSync(current, {withFileTypes: true});
+ } catch {
+ continue;
+ }
+ entries.sort((x, y) => x.name.localeCompare(y.name));
+ for (const entry of entries) {
+ if (++seen > AUGMENTATION_WALK_LIMIT) {
+ reason = `the package has more than ${AUGMENTATION_WALK_LIMIT} files to search for a \`declare module\` block, which can add names to its modules, so the names it imports were not checked`;
+ break walk;
+ }
+ const full = path.join(current, entry.name);
+ if (entry.isDirectory()) {
+ if (entry.name !== 'node_modules' && !entry.name.startsWith('.'))
+ queue.push(full);
+ continue;
+ }
+ if (!entry.isFile() || !TYPESCRIPT_FILE_RE.test(entry.name)) continue;
+ let text;
+ try {
+ text = fs.readFileSync(full, 'utf-8');
+ } catch {
+ continue;
+ }
+ if (augmentsOwnModule(ctx, text, entry.name)) {
+ reason = `"${rel(root, full)}" has a \`declare module\` block for a module of the package, which can add names to it, so the names it imports were not checked`;
+ break walk;
+ }
+ }
+ }
+ ctx.augmentation = reason;
+ return reason;
+}
+
+/**
+ * Why an import's names could not be judged.
+ * @param {string[]} files
+ * @param {boolean} [allPresent]
+ */
+function uncheckedReason(files, allPresent = true) {
+ if (files.length === 0 || !allPresent) {
+ return 'a file its package.json "exports" entry names does not exist yet (build output), so the names it imports were not checked';
+ }
+ return "its module's export list cannot be read in full (CommonJS, an `export *` from another package, a parse error, or JavaScript with no declaration file for its types), so the names it imports were not checked";
+}
+
+/**
+ * Whether `name` reads as a component: PascalCase, not ALL CAPS.
+ * @param {string} name
+ */
+function isComponentName(name) {
+ return /^[A-Z]/u.test(name) && /[a-z]/u.test(name);
+}
+
+/**
+ * The export a template's default export should be: an exported function or
+ * class first, else an exported `const`, each only when its name is
+ * PascalCase (not ALL CAPS) and not only a type; null when there is none to
+ * suggest (a hook such as `useAccount`, a helper such as `formatBalance`, a
+ * constant such as `ACCOUNT_LIMIT`), and then the fix stays generic.
+ * @param {string} text the template source
+ * @param {{names: Set<string>, types: Set<string>}} exported
+ * @returns {string | null}
+ */
+function defaultExportCandidate(text, exported) {
+ let body;
+ try {
+ body = parseModuleText(text).program.body;
+ } catch {
+ return null;
+ }
+ /** @type {Map<string, 'callable' | 'const'>} top-level bindings by kind */
+ const local = new Map();
+ /** @param {any} d */
+ const record = d => {
+ if (
+ (d?.type === 'FunctionDeclaration' || d?.type === 'ClassDeclaration') &&
+ d.id?.name
+ ) {
+ local.set(d.id.name, 'callable');
+ } else if (d?.type === 'VariableDeclaration' && d.kind === 'const') {
+ for (const v of d.declarations ?? []) {
+ if (v.id?.type === 'Identifier') local.set(v.id.name, 'const');
+ }
+ }
+ };
+ for (const node of body) {
+ record(node.type === 'ExportNamedDeclaration' ? node.declaration : node);
+ }
+ /** @type {{name: string, kind: 'callable' | 'const'}[]} */
+ const candidates = [];
+ for (const node of body) {
+ if (node.type !== 'ExportNamedDeclaration') continue;
+ const n = /** @type {any} */ (node);
+ if (n.exportKind === 'type') continue;
+ const d = n.declaration;
+ /** @type {string[]} */
+ const names = d
+ ? d.id?.name
+ ? [d.id.name]
+ : (d.declarations ?? [])
+ .map((/** @type {any} */ v) => v.id?.name)
+ .filter(Boolean)
+ : n.source
+ ? []
+ : (n.specifiers ?? [])
+ .filter((/** @type {any} */ sp) => sp.exportKind !== 'type')
+ .filter(
+ (/** @type {any} */ sp) =>
+ (sp.exported?.name ?? sp.exported?.value) === sp.local?.name,
+ )
+ .map((/** @type {any} */ sp) => sp.local.name);
+ for (const name of names) {
+ const kind = local.get(name);
+ if (kind) candidates.push({name, kind});
+ }
+ }
+ const fits = (/** @type {{name: string}} */ c) =>
+ isComponentName(c.name) && !exported.types.has(c.name);
+ return (
+ candidates.find(c => c.kind === 'callable' && fits(c))?.name ??
+ candidates.find(c => c.kind === 'const' && fits(c))?.name ??
+ null
+ );
+}
+
/**
* Whether `name` is a bare npm package name (an optional `@scope/` and a
* name), the only form an import can name the package by.
@@ -385,6 +947,9 @@ function listed(code, message) {
* @property {string | null} coreDir
* @property {any} corePkg
* @property {PublicImportUnchecked[]} unchecked what could not be judged
+ * @property {ExportNameCache} exportNames export lists read in this check
+ * @property {string | null} [augmentation] why no name is judged missing
+ * (a module augmentation in the package); null when none, unset until read
* @property {string[]} files the package.json `files` entries, normalized
* @property {string[]} roots the integration's contribution roots, absolute
*/
@@ -578,15 +1143,15 @@ function typesOnlyImport(ctx, statement, subpath, declaration) {
}
/**
- * Whether an import of the package's own name names a subpath `exports`
- * declares: the declaration when it does not, or the reason it was not
- * checked.
+ * How an import of the package's own name is judged: the declaration when
+ * `exports` does not declare its subpath, the names its module provably
+ * lacks, or the reason it was not checked.
* @param {Context} ctx
* @param {ImportStatement} statement
* @param {string} subpath
- * @returns {{undeclared: SubpathDeclaration | null, unchecked?: string}}
+ * @returns {{undeclared: SubpathDeclaration | null, missing: string[] | null, reason: string | null}}
*/
-function undeclaredOwnImport(ctx, statement, subpath) {
+function judgeOwnImport(ctx, statement, subpath) {
const declaration = declarationIn(ctx.exportsField, ctx.packageDir, subpath);
// A subpath an ES module import reaches only through `types` (any other
// condition beside it, such as `require`, loads nothing for it) is judged as
@@ -595,10 +1160,54 @@ function undeclaredOwnImport(ctx, statement, subpath) {
declaration.state === 'not_importable' &&
typesTargets(declaration.value, declaration.wildcard ?? '').length > 0
) {
- const unchecked = typesOnlyImport(ctx, statement, subpath, declaration);
- return unchecked ? {undeclared: null, unchecked} : {undeclared: null};
+ const reason = typesOnlyImport(ctx, statement, subpath, declaration);
+ return {undeclared: null, missing: [], reason};
+ }
+ if (declaration.state !== 'declared')
+ return {undeclared: declaration, missing: null, reason: null};
+ if (subpath === '.' && declaration.value == null) {
+ return {
+ undeclared: null,
+ missing: null,
+ reason:
+ 'package.json has no "exports", and the root module "main" names is not read, so the names it imports were not checked',
+ };
+ }
+ const {files, allPresent} = declaredTargets(ctx.packageDir, declaration);
+ const missing = missingNames(statement, files, ctx.exportNames, allPresent);
+ const augmented = missing?.length ? augmentationReason(ctx) : null;
+ if (augmented) return {undeclared: null, missing: null, reason: augmented};
+ return {
+ undeclared: null,
+ missing,
+ reason: missing == null ? uncheckedReason(files, allPresent) : null,
+ };
+}
+
+/**
+ * A declared subpath of the package whose module, read in full, exports
+ * `name`: the one the component's source is exported under first.
+ * @param {Context} ctx
+ * @param {string} name
+ * @param {string | null} preferred
+ * @returns {string | null}
+ */
+function subpathExporting(ctx, name, preferred) {
+ if (!isRecord(ctx.exportsField)) return null;
+ /** @param {string} subpath */
+ const exportsName = subpath =>
+ existingTargets(
+ ctx.packageDir,
+ declarationIn(ctx.exportsField, ctx.packageDir, subpath),
+ ).some(file => moduleExportNames(file, ctx.exportNames).names.has(name));
+ // The source's own subpath, which may come from a wildcard key, first.
+ if (preferred && exportsName(preferred)) return preferred;
+ for (const key of Object.keys(ctx.exportsField)) {
+ if (!key.startsWith('.') || key.includes('*') || key === preferred)
+ continue;
+ if (exportsName(key)) return key;
}
- return {undeclared: declaration.state === 'declared' ? null : declaration};
+ return null;
}
/**
@@ -688,7 +1297,66 @@ async function componentIssues(ctx, integration) {
specifier,
reason: unbuiltReason(split.subpath),
});
- } else if (declaration.state !== 'declared') {
+ } else if (
+ declaration.state === 'declared' &&
+ split.subpath === '.' &&
+ declaration.value == null
+ ) {
+ // A package with no exports resolves its root through main: not read.
+ ctx.unchecked.push({
+ file: shownDoc,
+ specifier,
+ reason:
+ 'package.json has no "exports", and the root module "main" names is not read, so the component names were not checked',
+ });
+ } else if (declaration.state === 'declared') {
+ // A doc whose `name` differs from the name it is listed under is
+ // judged by the doc-name check (`doc_name_mismatch`), never here.
+ const judged = list.filter(
+ r => typeof doc.name !== 'string' || doc.name === r.name,
+ );
+ const {files, allPresent} = declaredTargets(
+ ctx.packageDir,
+ declaration,
+ );
+ const statement = {
+ source: specifier,
+ names: judged.map(r => ({imported: r.name, typeOnly: false})),
+ namespace: false,
+ };
+ // A component is a run-time export, which no augmentation adds, so
+ // a missing one is reported whatever the package declares.
+ const missing =
+ judged.length === 0
+ ? []
+ : missingNames(statement, files, ctx.exportNames, allPresent, true);
+ if (missing == null) {
+ ctx.unchecked.push({
+ file: shownDoc,
+ specifier,
+ reason: uncheckedReason(files, allPresent),
+ });
+ }
+ for (const name of missing ?? []) {
+ const there = subpathExporting(ctx, name, declared);
+ // The per-component entry helps only when the component's source
+ // exports the name itself and the doc does not already use it.
+ const ownEntry =
+ perComponent != null &&
+ source != null &&
+ entryKey !== split.subpath &&
+ moduleExportNames(source, ctx.exportNames).names.has(name);
+ const fix = there
+ ? `set import: '${ctx.name}${there === '.' ? '' : there.slice(1)}' in the doc (that subpath exports it), or export "${name}" from the module "${specifier}" loads.`
+ : `export "${name}" from the module "${specifier}" loads${ownEntry ? `, or ${perComponent}` : ''}.`;
+ issues.push(
+ listed(
+ 'component_import_missing_name',
+ `Component doc "${shownDoc}" ${gives}, but that module does not export "${name}", so apps that follow the doc get nothing. Fix: ${fix}`,
+ ),
+ );
+ }
+ } else {
const already =
declared && declared !== split.subpath
? `set import: '${ctx.name}${declared.slice(1)}' (already exported), or `
@@ -703,18 +1371,69 @@ async function componentIssues(ctx, integration) {
}
/**
- * The `exports` entry an example with an undeclared import needs: its
- * subpath mapped to the file there, or to the component's source when
- * the example imports only components this doc documents, else to the
- * file that exports what it imports.
+ * Whether the module at a declared subpath exports every value name the
+ * statement imports (and it imports at least one).
+ * @param {ImportStatement} statement
+ * @param {string} candidate
+ */
+ const providesAll = (statement, candidate) => {
+ if (!statement.names.some(binding => !binding.typeOnly)) return false;
+ const declaration = declarationIn(
+ ctx.exportsField,
+ ctx.packageDir,
+ candidate,
+ );
+ if (declaration.state !== 'declared' || declaration.value == null)
+ return false;
+ const {files, allPresent} = declaredTargets(ctx.packageDir, declaration);
+ const missing = missingNames(
+ statement,
+ files,
+ ctx.exportNames,
+ allPresent,
+ );
+ return Array.isArray(missing) && missing.length === 0;
+ };
+
+ /**
+ * Where an example with an undeclared import should import from: the
+ * doc's own import, when it differs from the example's and is declared;
+ * else the subpath the component's source is already exported under;
+ * else the exact `exports` entry to add for the example's subpath.
+ * Another subpath is offered only when the statement imports at least one
+ * value name and its module provably exports every one of them.
* @param {ImportStatement} statement
* @param {string} subpath
* @param {SubpathDeclaration} undeclared
*/
const exampleFix = (statement, subpath, undeclared) => {
+ /** @param {string} candidate */
+ const provides = candidate => providesAll(statement, candidate);
const values = statement.names
.filter(binding => !binding.typeOnly)
.map(binding => binding.imported);
+ // A statement that imports no value name (a side-effect, namespace or
+ // all-type import) is never sent to another subpath: no names prove it.
+ const own = authored ? splitSpecifier(authored) : null;
+ if (
+ values.length > 0 &&
+ authored &&
+ authored !== statement.source &&
+ own?.pkg === ctx.name &&
+ provides(own.subpath)
+ ) {
+ return `import from '${authored}' in the example, as the doc's import does.`;
+ }
+ if (
+ values.length > 0 &&
+ declared &&
+ declared !== subpath &&
+ provides(declared)
+ ) {
+ return `import from '${ctx.name}${declared.slice(1)}' in the example (already exported).`;
+ }
+ // The entry for the example's own subpath: the file there, or the
+ // component's source when it exports every name, else a placeholder.
const atSubpath = [
'',
...MODULE_EXTENSIONS,
@@ -726,17 +1445,59 @@ async function componentIssues(ctx, integration) {
file.startsWith(path.resolve(ctx.packageDir) + path.sep) &&
isFile(file),
);
- const documented = new Set(list.map(r => r.name));
- const onlyDocumented =
- values.length > 0 && values.every(name => documented.has(name));
+ const sourceHasAll =
+ values.length > 0 &&
+ source != null &&
+ values.every(name =>
+ moduleExportNames(source, ctx.exportNames).names.has(name),
+ );
const target = atSubpath
? `./${rel(ctx.packageDir, atSubpath)}`
- : onlyDocumented && sourceTarget
+ : sourceHasAll && sourceTarget
? fixTarget(subpath, sourceTarget)
- : `<the file that exports ${values.join(', ') || 'them'}>`;
+ : values.length > 0
+ ? `<the file that exports ${values.join(', ')}>`
+ : '<the file it loads>';
return exportsFix(ctx.exportsField, undeclared.state, subpath, target);
};
+ /**
+ * The fix for an example that imports names its module lacks: import
+ * this doc's components that module does export, else the doc's own
+ * import when it differs, else export the names from it.
+ * @param {ImportStatement} statement
+ * @param {string} subpath
+ * @param {string[]} missing
+ */
+ const missingNameFix = (statement, subpath, missing) => {
+ const declaration = declarationIn(
+ ctx.exportsField,
+ ctx.packageDir,
+ subpath,
+ );
+ /** @type {Set<string>} */
+ const there = new Set();
+ for (const file of existingTargets(ctx.packageDir, declaration)) {
+ for (const name of moduleExportNames(file, ctx.exportNames).names)
+ there.add(name);
+ }
+ const docNames = list.map(r => r.name).filter(name => there.has(name));
+ const exportIt = `export ${missing.length === 1 ? 'the name' : 'the names'} from it`;
+ if (docNames.length > 0) {
+ return `import a name that module exports (${docNames.map(n => `"${n}"`).join(', ')} for this doc), or ${exportIt}.`;
+ }
+ const own = authored ? splitSpecifier(authored) : null;
+ if (
+ authored &&
+ authored !== statement.source &&
+ own?.pkg === ctx.name &&
+ providesAll(statement, own.subpath)
+ ) {
+ return `import from '${authored}', as the doc's import does, or ${exportIt}.`;
+ }
+ return `${exportIt[0].toUpperCase()}${exportIt.slice(1)}.`;
+ };
+
const examples = Array.isArray(doc.examples) ? doc.examples : [];
for (const [index, example] of examples.entries()) {
if (!isRecord(example) || typeof example.code !== 'string') continue;
@@ -747,21 +1508,19 @@ async function componentIssues(ctx, integration) {
for (const statement of readImports(example.code)) {
const parts = splitSpecifier(statement.source);
if (!parts || parts.pkg !== ctx.name) continue;
- const {undeclared, unchecked} = undeclaredOwnImport(
+ const {undeclared, missing, reason} = judgeOwnImport(
ctx,
statement,
parts.subpath,
);
- if (unchecked) {
+ if (reason) {
ctx.unchecked.push({
file: shownDoc,
specifier: statement.source,
- reason: `example ${label}: ${unchecked}`,
+ reason: `example ${label}: ${reason}`,
});
- } else if (
- undeclared &&
- unbuiltOutput(ctx, parts.subpath, undeclared)
- ) {
+ }
+ if (undeclared && unbuiltOutput(ctx, parts.subpath, undeclared)) {
ctx.unchecked.push({
file: shownDoc,
specifier: statement.source,
@@ -774,6 +1533,13 @@ async function componentIssues(ctx, integration) {
`Component doc "${shownDoc}" example ${label} imports "${statement.source}", but ${whyUndeclared(undeclared, parts.subpath)}, so the example fails when an app copies it. Fix: ${exampleFix(statement, parts.subpath, undeclared)}`,
),
);
+ } else if (missing && missing.length > 0) {
+ issues.push(
+ listed(
+ 'example_import_missing_name',
+ `Component doc "${shownDoc}" example ${label} imports ${missing.map(n => `"${n}"`).join(', ')} from "${statement.source}", which does not export ${missing.length === 1 ? 'it' : 'them'}, so the example fails when an app copies it. Fix: ${missingNameFix(statement, parts.subpath, missing)}`,
+ ),
+ );
}
}
}
@@ -824,6 +1590,27 @@ async function templateIssues(ctx, integration) {
} catch {
text = '';
}
+ // `astryx template` copies the source as written, but the package's
+ // public import, the gallery preview and a page that renders the
+ // template import its default export.
+ const exported = text ? moduleExportNames(file, ctx.exportNames) : null;
+ if (exported?.complete && !exported.names.has('default')) {
+ const named = defaultExportCandidate(text, exported);
+ const fix = named
+ ? `add \`export default ${named};\` to ${shown}, or make ${named} the default export`
+ : `export the template's component as the default export of ${shown} (\`export default function …\`)`;
+ // With no package name there is no public import to name.
+ const what =
+ ctx.name == null
+ ? 'anything that renders the template gets nothing'
+ : `its public import "${ctx.name}${subpath.slice(1)}" and anything that renders the template get nothing`;
+ issues.push(
+ listed(
+ 'template_no_default_export',
+ `Template "${id}" (${shown}) has no default export, so ${what}. Fix: ${fix}.`,
+ ),
+ );
+ }
for (const statement of readImports(text)) {
const spec = statement.source;
if (spec.startsWith('.')) {
@@ -841,17 +1628,15 @@ async function templateIssues(ctx, integration) {
const parts = splitSpecifier(spec);
if (!parts) continue;
if (ctx.name != null && parts.pkg === ctx.name) {
- const {undeclared, unchecked} = undeclaredOwnImport(
+ const {undeclared, missing, reason} = judgeOwnImport(
ctx,
statement,
parts.subpath,
);
- if (unchecked) {
- ctx.unchecked.push({file: shown, specifier: spec, reason: unchecked});
- } else if (
- undeclared &&
- unbuiltOutput(ctx, parts.subpath, undeclared)
- ) {
+ if (reason) {
+ ctx.unchecked.push({file: shown, specifier: spec, reason});
+ }
+ if (undeclared && unbuiltOutput(ctx, parts.subpath, undeclared)) {
ctx.unchecked.push({
file: shown,
specifier: spec,
@@ -864,6 +1649,13 @@ async function templateIssues(ctx, integration) {
`Template "${id}" (${shown}) imports "${spec}", but ${whyUndeclared(undeclared, parts.subpath)}, so the template breaks in an app. Fix: import from a subpath package.json "exports" declares, or add one for it.`,
),
);
+ } else if (missing && missing.length > 0) {
+ issues.push(
+ listed(
+ 'template_import_missing_name',
+ `Template "${id}" (${shown}) imports ${missing.map(n => `"${n}"`).join(', ')} from "${spec}", which does not export ${missing.length === 1 ? 'it' : 'them'}, so the template breaks in an app. Fix: import a name that module exports, or export the name from it.`,
+ ),
+ );
}
} else if (parts.pkg === CORE && !ctx.corePkg) {
ctx.unchecked.push({
@@ -952,6 +1744,7 @@ export async function publicImportIssues(packageDir, integration) {
coreDir: isCore ? foundCore : null,
corePkg: isCore ? foundCorePkg : null,
unchecked: report.unchecked,
+ exportNames: new Map(),
files: Array.isArray(pkg.files)
? pkg.files
.filter(entry => typeof entry === 'string')
diff --git a/packages/cli/foundation/integrations/public-imports.test.mjs b/packages/cli/foundation/integrations/public-imports.test.mjs
index 6a826d8bea..a3f8899e3a 100644
--- a/packages/cli/foundation/integrations/public-imports.test.mjs
+++ b/packages/cli/foundation/integrations/public-imports.test.mjs
@@ -32,10 +32,14 @@ import {CLI_ROOT} from '../fs/paths.mjs';
const CODES = new Set([
'component_import_not_exported',
'component_import_other_package',
+ 'component_import_missing_name',
'example_import_not_exported',
+ 'example_import_missing_name',
'template_import_not_exported',
'template_import_outside_root',
'template_private_import',
+ 'template_import_missing_name',
+ 'template_no_default_export',
]);
let dir;
@@ -284,7 +288,7 @@ describe('public imports: component doc import', () => {
});
write(
'templates/account-card.tsx',
- "import {X} from '../components/AcmeWidget';\nexport function A() {\n return <X />;\n}\n",
+ "import {X} from '../components/AcmeWidget';\nexport default function A() {\n return <X />;\n}\n",
);
const issues = await found();
expect(issues.length).toBeGreaterThan(2);
@@ -364,6 +368,58 @@ describe('public imports: component doc import', () => {
});
describe('public imports: component examples', () => {
+ it('flags a name the package does not export', async () => {
+ write(
+ 'components/AcmeWidget.doc.mjs',
+ DOC(
+ undefined,
+ "import {AcmeGadget} from '@acme/widgets/components/AcmeWidget';\\n<AcmeGadget />",
+ ),
+ );
+ expect(await codes()).toEqual(['example_import_missing_name']);
+ const issue = (await found()).find(
+ i => i.code === 'example_import_missing_name',
+ );
+ expect(issue?.message).toContain(
+ 'import a name that module exports ("AcmeWidget" for this doc)',
+ );
+ });
+
+ it("points a missing-name example at the doc's import only when that module exports the missing name", async () => {
+ pkg(p => {
+ p.exports['./other'] = './lib/other.ts';
+ });
+ write('lib/other.ts', 'export const Unrelated = 1;\n');
+ write(
+ 'components/AcmeWidget.tsx',
+ 'export function AcmeWidget() {\n return null;\n}\nexport function AcmeGadget() {\n return null;\n}\n',
+ );
+ write(
+ 'components/AcmeWidget.doc.mjs',
+ DOC(
+ undefined,
+ "import {AcmeGadget} from '@acme/widgets/other';\\n<AcmeGadget />",
+ ),
+ );
+ const issue = (await found()).find(
+ i => i.code === 'example_import_missing_name',
+ );
+ expect(issue?.message).not.toContain('for this doc');
+ expect(issue?.message).toContain(
+ "import from '@acme/widgets/components/AcmeWidget', as the doc's import does",
+ );
+ // Without the name there, the doc's import is no fix.
+ write(
+ 'components/AcmeWidget.tsx',
+ 'export function AcmeWidget() {\n return null;\n}\n',
+ );
+ const generic = (await found()).find(
+ i => i.code === 'example_import_missing_name',
+ );
+ expect(generic?.message).toContain('Fix: Export the name from it.');
+ expect(generic?.message).not.toContain("as the doc's import does");
+ });
+
it('flags a subpath exports does not declare', async () => {
write(
'components/AcmeWidget.doc.mjs',
@@ -375,6 +431,22 @@ describe('public imports: component examples', () => {
expect(await codes()).toEqual(['example_import_not_exported']);
});
+ it('points an undeclared example import at the doc import when that is declared', async () => {
+ write(
+ 'components/AcmeWidget.doc.mjs',
+ DOC(
+ undefined,
+ "import {AcmeWidget} from '@acme/widgets/src/AcmeWidget';\\n<AcmeWidget />",
+ ),
+ );
+ const issue = (await found()).find(
+ i => i.code === 'example_import_not_exported',
+ );
+ expect(issue?.message).toContain(
+ "Fix: import from '@acme/widgets/components/AcmeWidget' in the example, as the doc's import does.",
+ );
+ });
+
it('never points an example back at the same undeclared doc import', async () => {
pkg(p => delete p.exports['./components/AcmeWidget']);
const issue = (await found()).find(
@@ -409,6 +481,61 @@ describe('public imports: component examples', () => {
);
});
+ it('never points a side-effect import of an undeclared subpath at another subpath', async () => {
+ write('styles.css', '.acme {}\n');
+ write(
+ 'components/AcmeWidget.doc.mjs',
+ DOC(undefined, "import '@acme/widgets/styles.css';\\n<AcmeWidget />"),
+ );
+ const issue = (await found()).find(
+ i => i.code === 'example_import_not_exported',
+ );
+ expect(issue?.message).not.toContain('in the example');
+ expect(issue?.message).toContain(
+ 'add "./styles.css": "./styles.css" to package.json "exports"',
+ );
+ });
+
+ it('points an example at the subpath the source is already exported under', async () => {
+ pkg(p => {
+ delete p.exports['./components/AcmeWidget'];
+ p.exports['./widget'] = './components/AcmeWidget.tsx';
+ });
+ write(
+ 'components/AcmeWidget.doc.mjs',
+ DOC(
+ '@acme/widgets/nope',
+ "import {AcmeWidget} from '@acme/widgets/nope';\\n<AcmeWidget />",
+ ),
+ );
+ const issue = (await found()).find(
+ i => i.code === 'example_import_not_exported',
+ );
+ expect(issue?.message).toContain(
+ "Fix: import from '@acme/widgets/widget' in the example (already exported).",
+ );
+ });
+
+ it('leaves a CommonJS target unjudged for names', async () => {
+ write(
+ 'components/AcmeWidget.doc.mjs',
+ DOC(
+ undefined,
+ "import {AcmeGadget} from '@acme/widgets/components/AcmeWidget';\\n<AcmeGadget />",
+ ),
+ );
+ write(
+ 'components/AcmeWidget.tsx',
+ 'module.exports = {AcmeWidget: () => null, AcmeGadget: () => null};\n',
+ );
+ expect(await codes()).toEqual([]);
+ pkg(p => {
+ p.exports['./components/AcmeWidget'] = './components/AcmeWidget.cjs';
+ });
+ write('components/AcmeWidget.cjs', 'export const Other = 1;\n');
+ expect(await codes()).toEqual([]);
+ });
+
it('accepts aliased, type-only and other-package imports', async () => {
write(
'components/AcmeWidget.doc.mjs',
@@ -460,6 +587,60 @@ describe('public imports: template sources', () => {
expect(await codes()).toEqual([]);
});
+ it('flags a name its own package does not export', async () => {
+ write(
+ 'templates/account-card.tsx',
+ 'import {AcmeGadget} from \'@acme/widgets/components/AcmeWidget\';\nexport default function A() {\n return <AcmeGadget label="x" />;\n}\n',
+ );
+ expect(await codes()).toEqual(['template_import_missing_name']);
+ });
+
+ it('leaves a built CommonJS dist file reached through exports unjudged for names', async () => {
+ pkg(p => {
+ p.exports['./components/AcmeWidget'] = {
+ types: './dist/AcmeWidget.d.ts',
+ default: './dist/AcmeWidget.js',
+ };
+ });
+ write(
+ 'dist/AcmeWidget.js',
+ "'use strict';\nObject.defineProperty(exports, '__esModule', {value: true});\nexports.AcmeWidget = void 0;\nconst AcmeWidget = () => null;\nexports.AcmeWidget = AcmeWidget;\n",
+ );
+ write(
+ 'templates/account-card.tsx',
+ 'import {AcmeGadget} from \'@acme/widgets/components/AcmeWidget\';\nexport default function A() {\n return <AcmeGadget label="x" />;\n}\n',
+ );
+ write(
+ 'components/AcmeWidget.doc.mjs',
+ DOC(
+ undefined,
+ "import {AcmeGadget} from '@acme/widgets/components/AcmeWidget';\\n<AcmeGadget />",
+ ),
+ );
+ expect(await codes()).toEqual([]);
+ });
+
+ it('leaves a module that also assigns exports.* unjudged for names', async () => {
+ write(
+ 'components/AcmeWidget.tsx',
+ 'export function AcmeWidget() {\n return null;\n}\nexports.AcmeGadget = AcmeWidget;\n',
+ );
+ write(
+ 'templates/account-card.tsx',
+ 'import {AcmeGadget} from \'@acme/widgets/components/AcmeWidget\';\nexport default function A() {\n return <AcmeGadget label="x" />;\n}\n',
+ );
+ expect(await codes()).toEqual([]);
+ });
+
+ it('leaves a CommonJS target of a template import unjudged for names', async () => {
+ write('components/AcmeWidget.tsx', 'exports.AcmeWidget = () => null;\n');
+ write(
+ 'templates/account-card.tsx',
+ 'import {AcmeGadget} from \'@acme/widgets/components/AcmeWidget\';\nexport default function A() {\n return <AcmeGadget label="x" />;\n}\n',
+ );
+ expect(await codes()).toEqual([]);
+ });
+
it('flags a template whose public import exports does not declare', async () => {
pkg(p => delete p.exports['./templates/account-card']);
const issue = (await found()).find(
@@ -471,6 +652,38 @@ describe('public imports: template sources', () => {
});
});
+describe('template default export', () => {
+ it('lists a template source with no default export, naming the export to add', async () => {
+ write(
+ 'templates/account-card.tsx',
+ 'export function AccountCard() {\n return <div>Account</div>;\n}\n',
+ );
+ const issues = await found();
+ expect(issues.map(i => i.code)).toEqual(['template_no_default_export']);
+ expect(issues[0].message).toContain('export default AccountCard;');
+ });
+
+ it('suggests a value, never a type, as the default export', async () => {
+ write(
+ 'templates/account-card.tsx',
+ 'export interface AccountCardProps {\n title: string;\n}\nexport type AccountCardSize = "sm";\nexport function AccountCard() {\n return <div>Account</div>;\n}\n',
+ );
+ const issue = (await found()).find(
+ i => i.code === 'template_no_default_export',
+ );
+ expect(issue?.message).toContain('export default AccountCard;');
+ expect(issue?.message).not.toContain('AccountCardProps;');
+ });
+
+ it('accepts a re-exported or type-annotated default', async () => {
+ write(
+ 'templates/account-card.tsx',
+ 'function AccountCard() {\n return <div>Account</div>;\n}\nexport {AccountCard as default};\n',
+ );
+ expect(await codes()).toEqual([]);
+ });
+});
+
describe('subpathDeclaration', () => {
it('reads each way exports can declare a subpath', () => {
expect(subpathDeclaration(undefined, './a').state).toBe('no_exports');
@@ -504,6 +717,43 @@ describe('derived component imports', () => {
};
`;
+ it('warns when the derived root import does not export the component, naming the subpath that does', async () => {
+ write('components/AcmeWidget.doc.mjs', NO_IMPORT);
+ write('index.js', 'export const Other = 1;\n');
+ pkg(p => {
+ p.exports['.'] = './index.js';
+ });
+ const issues = (await found()).filter(
+ i => i.code === 'component_import_missing_name',
+ );
+ expect(issues).toHaveLength(1);
+ expect(issues[0].message).toContain(
+ 'has no import, so apps are told to import from "@acme/widgets"',
+ );
+ expect(issues[0].message).toContain(
+ "set import: '@acme/widgets/components/AcmeWidget' in the doc",
+ );
+ });
+
+ it('names the wildcard subpath the component is already exported under', async () => {
+ write('index.js', 'export const Other = 1;\n');
+ pkg(p => {
+ p.exports = {
+ '.': './index.js',
+ './components/*': './components/*.tsx',
+ './templates/account-card': './templates/account-card.tsx',
+ };
+ });
+ write('components/AcmeWidget.doc.mjs', DOC('@acme/widgets'));
+ const issue = (await found()).find(
+ i => i.code === 'component_import_missing_name',
+ );
+ expect(issue?.message).toContain(
+ "set import: '@acme/widgets/components/AcmeWidget' in the doc (that subpath exports it)",
+ );
+ expect(issue?.message).not.toContain('add "./components/AcmeWidget"');
+ });
+
it('warns when the derived root import is not declared', async () => {
write('components/AcmeWidget.doc.mjs', NO_IMPORT);
const issue = (await found()).find(
@@ -513,6 +763,51 @@ describe('derived component imports', () => {
'has no import, so apps are told to import from "@acme/widgets"',
);
});
+
+ it('warns when a written import does not export the component', async () => {
+ write('index.js', 'export const Other = 1;\n');
+ pkg(p => {
+ p.exports['.'] = './index.js';
+ });
+ write('components/AcmeWidget.doc.mjs', DOC('@acme/widgets'));
+ expect(await codes()).toContain('component_import_missing_name');
+ });
+
+ it('warns when a written import does not export the component, even while the package augments a module', async () => {
+ write('index.js', 'export const Other = 1;\n');
+ write(
+ 'types/augment.d.ts',
+ "declare module '@acme/widgets' {\n interface AcmeTone {}\n}\nexport {};\n",
+ );
+ pkg(p => {
+ p.exports['.'] = './index.js';
+ });
+ write('components/AcmeWidget.doc.mjs', DOC('@acme/widgets'));
+ expect(await codes()).toContain('component_import_missing_name');
+ });
+
+ it('lists a derived import whose target is not built as not checked', async () => {
+ write('components/AcmeWidget.doc.mjs', NO_IMPORT);
+ pkg(p => {
+ p.exports['.'] = {types: './dist/index.d.ts', import: './dist/index.js'};
+ });
+ const result = await validateIntegration(undefined, {cwd: dir});
+ expect(
+ (result.data.notes ?? []).filter(i =>
+ i.code.startsWith('component_import'),
+ ),
+ ).toEqual([]);
+ expect(result.data.publicImports?.unchecked).toEqual([
+ expect.objectContaining({
+ file: 'components/AcmeWidget.doc.mjs',
+ specifier: '@acme/widgets',
+ reason: expect.stringContaining('build output'),
+ }),
+ ]);
+ const check = await integrationCheck({cwd: dir, strict: true});
+ expect(check.data.unchecked).toBe(1);
+ expect(check.data.failed).toBe(false);
+ });
});
describe('fixes for two components in one folder', () => {
@@ -547,6 +842,44 @@ describe('fixes for two components in one folder', () => {
);
for (const fix of fixes) expect(fix).not.toContain('".":');
});
+
+ it('gives each a per-component entry when the derived folder subpath lacks it', async () => {
+ write('components/index.js', 'export const Other = 1;\n');
+ pkg(p => {
+ p.exports['./components'] = './components/index.js';
+ p.exports['.'] = './components/index.js';
+ });
+ const fixes = (await found())
+ .filter(i => i.code === 'component_import_missing_name')
+ .map(i => i.message.split('Fix: ')[1]);
+ expect(fixes).toHaveLength(2);
+ expect(fixes[0]).toContain(
+ `add "./components/AcmeAlpha": "./components/AcmeAlpha.tsx" to package.json "exports" and set import: '@acme/widgets/components/AcmeAlpha' in the doc`,
+ );
+ expect(fixes[1]).toContain(
+ '"./components/AcmeBeta": "./components/AcmeBeta.tsx"',
+ );
+ for (const fix of fixes) expect(fix).not.toContain('"./components":');
+ });
+
+ it('never offers a per-component entry when the source exports the component only as default', async () => {
+ write('components/index.js', 'export const Other = 1;\n');
+ write(
+ 'components/AcmeAlpha.tsx',
+ 'export default function AcmeAlpha() {\n return null;\n}\n',
+ );
+ pkg(p => {
+ p.exports['./components'] = './components/index.js';
+ p.exports['.'] = './components/index.js';
+ });
+ const fix = (await found())
+ .filter(i => i.code === 'component_import_missing_name')
+ .map(i => i.message.split('Fix: ')[1])
+ .find(text => text.includes('"AcmeAlpha"'));
+ expect(fix).toBe(
+ 'export "AcmeAlpha" from the module "@acme/widgets/components" loads.',
+ );
+ });
});
describe('type-only imports', () => {
@@ -698,29 +1031,6 @@ describe('an empty exports map', () => {
});
});
-describe('a fresh scaffold passes the checks', () => {
- for (const exportsMap of [undefined, {'.': './index.js'}]) {
- it(`with ${exportsMap ? 'an' : 'no'} exports map`, async () => {
- fs.rmSync(dir, {recursive: true, force: true});
- fs.mkdirSync(dir);
- write(
- 'package.json',
- JSON.stringify({
- name: '@acme/fresh',
- version: '1.0.0',
- type: 'module',
- ...(exportsMap ? {exports: exportsMap} : {}),
- }),
- );
- write('index.js', 'export {};\n');
- await integrationAddComponent('AcmeThing', {cwd: dir});
- await integrationAddTemplate('acme-page', {cwd: dir});
- const check = await integrationCheck({cwd: dir, strict: true});
- expect(check.data.failures).toEqual([]);
- });
- }
-});
-
describe('imports listed as not checked', () => {
it('lists a template import of Core when Core is not installed', () => {
const out = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-no-core-'));
@@ -775,30 +1085,225 @@ describe('imports listed as not checked', () => {
fs.rmSync(out, {recursive: true, force: true});
}
}, 60_000);
+
+ it('lists template and example imports whose names cannot be judged', async () => {
+ pkg(p => {
+ p.exports['./built'] = './dist/built.js';
+ p.exports['./cjs'] = './cjs.cjs';
+ });
+ write('cjs.cjs', 'module.exports = {A: 1};\n');
+ write(
+ 'templates/account-card.tsx',
+ "import {Built} from '@acme/widgets/built';\nimport {A} from '@acme/widgets/cjs';\nimport {AcmeWidget} from '@acme/widgets/components/AcmeWidget';\nexport default function C() {\n return <AcmeWidget label=\"x\" />;\n}\n",
+ );
+ const result = await validateIntegration(undefined, {cwd: dir});
+ expect(result.data.issues).toEqual([]);
+ expect(
+ result.data.publicImports?.unchecked.map(u => [u.file, u.specifier]),
+ ).toEqual([
+ ['templates/account-card.tsx', '@acme/widgets/built'],
+ ['templates/account-card.tsx', '@acme/widgets/cjs'],
+ ]);
+ const check = await integrationCheck({cwd: dir, strict: true});
+ expect(check.data.unchecked).toBe(2);
+ expect(check.data.failed).toBe(false);
+ });
});
-describe('which Core and which package', () => {
- it("lists Core imports as not checked when the found core is a workspace's own package", async () => {
- // An npm-workspaces monorepo: its own packages/core is @acme/core, and
- // the integration lives in packages/widgets.
- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-workspace-'));
- try {
- const put = (/** @type {string} */ rel, /** @type {string} */ text) => {
- fs.mkdirSync(path.dirname(path.join(root, rel)), {recursive: true});
- fs.writeFileSync(path.join(root, rel), text);
- };
- put(
- 'package.json',
- JSON.stringify({
- name: 'acme-monorepo',
- private: true,
- workspaces: ['packages/*'],
- }),
- );
- put(
- 'packages/core/package.json',
- JSON.stringify({
- name: '@acme/core',
+describe('a root import in a package with no exports', () => {
+ it('says the package has no exports map', async () => {
+ pkg(p => delete p.exports);
+ write(
+ 'templates/account-card.tsx',
+ 'import {AcmeWidget} from \'@acme/widgets\';\nexport default function C() {\n return <AcmeWidget label="x" />;\n}\n',
+ );
+ const result = await validateIntegration(undefined, {cwd: dir});
+ const entry = result.data.publicImports?.unchecked.find(
+ u => u.file === 'templates/account-card.tsx',
+ );
+ expect(entry?.reason).toContain('package.json has no "exports"');
+ expect(entry?.reason).not.toContain('build output');
+ });
+});
+
+describe('a fresh scaffold passes the checks', () => {
+ for (const exportsMap of [undefined, {'.': './index.js'}]) {
+ it(`with ${exportsMap ? 'an' : 'no'} exports map`, async () => {
+ fs.rmSync(dir, {recursive: true, force: true});
+ fs.mkdirSync(dir);
+ write(
+ 'package.json',
+ JSON.stringify({
+ name: '@acme/fresh',
+ version: '1.0.0',
+ type: 'module',
+ ...(exportsMap ? {exports: exportsMap} : {}),
+ }),
+ );
+ write('index.js', 'export {};\n');
+ await integrationAddComponent('AcmeThing', {cwd: dir});
+ await integrationAddTemplate('acme-page', {cwd: dir});
+ const check = await integrationCheck({cwd: dir, strict: true});
+ expect(check.data.failures).toEqual([]);
+ });
+ }
+});
+
+describe('export * cycles and repeated checks', () => {
+ beforeEach(() => {
+ pkg(p => {
+ p.exports['./a'] = './lib/a.ts';
+ p.exports['./b'] = './lib/b.ts';
+ });
+ write('lib/a.ts', "export const A = 1;\nexport * from './b';\n");
+ write('lib/b.ts', "export * from './a';\nexport const B = 2;\n");
+ });
+
+ it('reads every name through an export * cycle, from either side', async () => {
+ write(
+ 'templates/account-card.tsx',
+ "import {A, B} from '@acme/widgets/a';\nimport {A as A2, B as B2} from '@acme/widgets/b';\nimport {AcmeWidget} from '@acme/widgets/components/AcmeWidget';\nexport default function C() {\n return <AcmeWidget label={String(A + B + A2 + B2)} />;\n}\n",
+ );
+ expect(await codes()).toEqual([]);
+ });
+
+ it('rereads a re-exported module on a second check in the same process', async () => {
+ write('lib/b.ts', 'export const B = 2;\n');
+ write('lib/c.ts', "export * from './b';\n");
+ pkg(p => {
+ p.exports['./c'] = './lib/c.ts';
+ });
+ write(
+ 'templates/account-card.tsx',
+ "import {C} from '@acme/widgets/c';\nexport default function T() {\n return <div>{C}</div>;\n}\n",
+ );
+ expect(await codes()).toEqual(['template_import_missing_name']);
+ // Fix only the re-exported module: c.ts itself does not change.
+ write('lib/b.ts', 'export const B = 2;\nexport const C = 3;\n');
+ expect(await codes()).toEqual([]);
+ });
+});
+
+describe('export import declarations', () => {
+ it('counts `export import Alias = Inner.Value` as an exported name', async () => {
+ pkg(p => {
+ p.exports['./ns'] = './lib/ns.ts';
+ });
+ write(
+ 'lib/ns.ts',
+ 'namespace Inner {\n export const Value = 1;\n}\nexport const Other = 2;\nexport import Alias = Inner.Value;\n',
+ );
+ write(
+ 'templates/account-card.tsx',
+ "import {Alias} from '@acme/widgets/ns';\nexport default function C() {\n return <div>{Alias}</div>;\n}\n",
+ );
+ expect(await codes()).toEqual([]);
+ });
+
+ it('leaves a module with a type-only export import unjudged', async () => {
+ pkg(p => {
+ p.exports['./ns'] = './lib/ns.ts';
+ });
+ write(
+ 'lib/ns.ts',
+ "export const Kept = 1;\nexport import type Alias = require('./other');\n",
+ );
+ write(
+ 'templates/account-card.tsx',
+ "import {Other} from '@acme/widgets/ns';\nexport default function C() {\n return <div>{Other}</div>;\n}\n",
+ );
+ const result = await validateIntegration(undefined, {cwd: dir});
+ expect(
+ (result.data.notes ?? []).filter(
+ i => i.code === 'template_import_missing_name',
+ ),
+ ).toEqual([]);
+ expect(
+ result.data.publicImports?.unchecked.map(u => u.specifier),
+ ).toContain('@acme/widgets/ns');
+ });
+});
+
+describe('types from a built package', () => {
+ it('reads a type re-exported through export * in a declaration file', async () => {
+ pkg(p => {
+ p.exports['./widget'] = {
+ types: './dist/widget.d.ts',
+ import: './dist/widget.js',
+ };
+ });
+ write(
+ 'dist/widget.js',
+ "export * from './types.js';\nexport const AcmeWidget = () => null;\n",
+ );
+ write(
+ 'dist/widget.d.ts',
+ "export * from './types.js';\nexport declare const AcmeWidget: () => null;\n",
+ );
+ write('dist/types.js', 'export {};\n');
+ write(
+ 'dist/types.d.ts',
+ 'export interface AcmeWidgetProps {\n label: string;\n}\n',
+ );
+ write(
+ 'templates/account-card.tsx',
+ "import {AcmeWidget, AcmeWidgetProps} from '@acme/widgets/widget';\nexport default function C(props: AcmeWidgetProps) {\n return <AcmeWidget {...props} />;\n}\n",
+ );
+ expect(await codes()).toEqual([]);
+ });
+
+ it('reads the declaration file beside a .js export target', async () => {
+ pkg(p => {
+ p.exports['./built'] = './dist/built.js';
+ });
+ write('dist/built.js', 'export const AcmeThing = 1;\n');
+ write(
+ 'dist/built.d.ts',
+ 'export declare const AcmeThing: number;\nexport type AcmeThingSize = "sm" | "md";\n',
+ );
+ write(
+ 'templates/account-card.tsx',
+ "import {AcmeThing, AcmeThingSize} from '@acme/widgets/built';\nexport default function C() {\n const size: AcmeThingSize = 'sm';\n return <div>{AcmeThing}{size}</div>;\n}\n",
+ );
+ expect(await codes()).toEqual([]);
+ });
+
+ it('still warns on a name neither the module nor its declarations export', async () => {
+ pkg(p => {
+ p.exports['./built'] = './dist/built.js';
+ });
+ write('dist/built.js', 'export const AcmeThing = 1;\n');
+ write('dist/built.d.ts', 'export declare const AcmeThing: number;\n');
+ write(
+ 'templates/account-card.tsx',
+ "import {AcmeOther} from '@acme/widgets/built';\nexport default function C() {\n return <div>{AcmeOther}</div>;\n}\n",
+ );
+ expect(await codes()).toEqual(['template_import_missing_name']);
+ });
+});
+
+describe('which Core and which package', () => {
+ it("lists Core imports as not checked when the found core is a workspace's own package", async () => {
+ // An npm-workspaces monorepo: its own packages/core is @acme/core, and
+ // the integration lives in packages/widgets.
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-workspace-'));
+ try {
+ const put = (/** @type {string} */ rel, /** @type {string} */ text) => {
+ fs.mkdirSync(path.dirname(path.join(root, rel)), {recursive: true});
+ fs.writeFileSync(path.join(root, rel), text);
+ };
+ put(
+ 'package.json',
+ JSON.stringify({
+ name: 'acme-monorepo',
+ private: true,
+ workspaces: ['packages/*'],
+ }),
+ );
+ put(
+ 'packages/core/package.json',
+ JSON.stringify({
+ name: '@acme/core',
version: '1.0.0',
exports: {'.': './index.js'},
}),
@@ -866,3 +1371,423 @@ describe('which Core and which package', () => {
).toEqual([]);
});
});
+
+describe('what the export-list reader does not model is not checked', () => {
+ const template = (/** @type {string} */ names, /** @type {string} */ from) =>
+ `import {${names}} from '${from}';\nexport default function C() {\n return <div />;\n}\n`;
+
+ it('lists a name as not checked when a declared types target is not built yet', async () => {
+ pkg(p => {
+ p.exports['./widget'] = {
+ types: './dist/widget.d.ts',
+ import: './src/widget.ts',
+ };
+ });
+ write('src/widget.ts', 'export const AcmeThing = 1;\n');
+ write(
+ 'templates/account-card.tsx',
+ template('AcmeThing, AcmeThingProps', '@acme/widgets/widget'),
+ );
+ const result = await validateIntegration(undefined, {cwd: dir});
+ expect(await codes()).toEqual([]);
+ expect(result.data.publicImports?.unchecked).toEqual([
+ expect.objectContaining({
+ specifier: '@acme/widgets/widget',
+ reason: expect.stringContaining('does not exist yet'),
+ }),
+ ]);
+ });
+
+ it('resolves a .js specifier in TypeScript source to the .ts file beside it', async () => {
+ pkg(p => {
+ p.exports['./widget'] = './src/widget.ts';
+ });
+ write('src/widget.ts', "export * from './inner.js';\n");
+ write('src/inner.ts', 'export const Inner = 1;\nexport const Newer = 2;\n');
+ // A stale build of inner beside its source, without the newer export.
+ write('src/inner.js', 'export const Inner = 1;\n');
+ write(
+ 'templates/account-card.tsx',
+ template('Newer', '@acme/widgets/widget'),
+ );
+ expect(await codes()).toEqual([]);
+ });
+
+ it('reads the declaration file beside a module an export * reaches', async () => {
+ pkg(p => {
+ p.exports['./widget'] = './dist/index.js';
+ });
+ write('dist/index.js', "export * from './inner.js';\n");
+ write('dist/inner.js', 'export const Inner = 1;\n');
+ write(
+ 'dist/inner.d.ts',
+ 'export declare const Inner: number;\nexport interface InnerProps {\n size: string;\n}\n',
+ );
+ write(
+ 'templates/account-card.tsx',
+ template('Inner, InnerProps', '@acme/widgets/widget'),
+ );
+ expect(await codes()).toEqual([]);
+ });
+
+ it('does not judge a name a JavaScript module without declarations lacks, since it may be a type', async () => {
+ pkg(p => {
+ p.exports['./widget'] = './dist/widget.js';
+ });
+ write('dist/widget.js', 'export const AcmeThing = 1;\n');
+ write(
+ 'templates/account-card.tsx',
+ template('AcmeThing, AcmeThingProps', '@acme/widgets/widget'),
+ );
+ const result = await validateIntegration(undefined, {cwd: dir});
+ expect(await codes()).toEqual([]);
+ expect(result.data.publicImports?.unchecked.map(u => u.specifier)).toEqual([
+ '@acme/widgets/widget',
+ ]);
+ });
+});
+
+describe('declaration files follow TypeScript', () => {
+ const template = (/** @type {string} */ names) =>
+ `import {${names}} from '@acme/widgets/widget';\nexport default function C() {\n return <div />;\n}\n`;
+
+ beforeEach(() => {
+ pkg(p => {
+ p.exports['./widget'] = './dist/widget.js';
+ });
+ write('dist/widget.js', 'export const AcmeWidget = () => null;\n');
+ });
+
+ it('counts every top-level declaration of a declaration-file module as exported', async () => {
+ write(
+ 'dist/widget.d.ts',
+ 'interface AcmeWidgetProps {\n label: string;\n}\nexport declare const AcmeWidget: (p: AcmeWidgetProps) => null;\n',
+ );
+ write(
+ 'templates/account-card.tsx',
+ template('AcmeWidget, AcmeWidgetProps'),
+ );
+ expect(await codes()).toEqual([]);
+ });
+
+ it('exports only what is listed once the declaration file has an export list', async () => {
+ write(
+ 'dist/widget.d.ts',
+ 'interface AcmeWidgetProps {\n label: string;\n}\ndeclare const AcmeWidget: (p: AcmeWidgetProps) => null;\nexport {AcmeWidget};\n',
+ );
+ write(
+ 'templates/account-card.tsx',
+ template('AcmeWidget, AcmeWidgetProps'),
+ );
+ expect(await codes()).toEqual(['template_import_missing_name']);
+ });
+
+ // A `declare module './widget.js'` block in a file widget.d.ts loads adds
+ // names widget.d.ts itself does not list.
+ const AUGMENT =
+ "import './widget.js';\ndeclare module './widget.js' {\n interface AcmeWidgetSize {\n value: string;\n }\n}\nexport {};\n";
+ const LISTED =
+ 'declare const AcmeWidget: () => null;\nexport {AcmeWidget};\n';
+
+ for (const [form, head] of [
+ ['a side-effect import', "import './augment.js';\n"],
+ ['a reference directive', '/// <reference path="./augment.d.ts" />\n'],
+ ]) {
+ it(`does not report a name added by augmentation in a file loaded through ${form}`, async () => {
+ write('dist/augment.d.ts', AUGMENT);
+ write('dist/widget.d.ts', `${head}${LISTED}`);
+ write(
+ 'templates/account-card.tsx',
+ template('AcmeWidget, AcmeWidgetSize'),
+ );
+ const result = await validateIntegration(undefined, {cwd: dir});
+ expect(await codes()).toEqual([]);
+ expect(
+ result.data.publicImports?.unchecked.map(u => u.specifier),
+ ).toEqual(['@acme/widgets/widget']);
+ });
+ }
+
+ it('still reports a missing name when no file in the package augments a module', async () => {
+ write('dist/widget.d.ts', LISTED);
+ write('templates/account-card.tsx', template('AcmeWidget, AcmeWidgetSize'));
+ expect(await codes()).toEqual(['template_import_missing_name']);
+ });
+
+ it.each([
+ [
+ 'a `declare module` example in a JSDoc comment',
+ "/**\n * @example\n * declare module './widget.js' {\n * interface AcmeWidgetSize {}\n * }\n */\nexport type AcmeTone = 'a';\n",
+ ],
+ [
+ 'a wildcard `declare module`',
+ "declare module '*.doc.mjs' {\n const doc: unknown;\n export default doc;\n}\n",
+ ],
+ [
+ 'a `declare global` block',
+ 'declare global {\n interface AcmeGlobal {}\n}\nexport {};\n',
+ ],
+ [
+ "an augmentation of another package's module",
+ "declare module '@astryxdesign/core' {\n interface AcmeTone {}\n}\nexport {};\n",
+ ],
+ ])('still reports a missing name beside %s', async (_label, text) => {
+ write('dist/augment.d.ts', text);
+ write('dist/widget.d.ts', LISTED);
+ write('templates/account-card.tsx', template('AcmeWidget, AcmeWidgetSize'));
+ expect(await codes()).toEqual(['template_import_missing_name']);
+ });
+
+ it("lists a name as not checked when a file augments the package's own name", async () => {
+ write(
+ 'types/augment.d.ts',
+ "declare module '@acme/widgets/widget' {\n interface AcmeWidgetSize {}\n}\nexport {};\n",
+ );
+ write('dist/widget.d.ts', LISTED);
+ write('templates/account-card.tsx', template('AcmeWidget, AcmeWidgetSize'));
+ const result = await validateIntegration(undefined, {cwd: dir});
+ expect(await codes()).toEqual([]);
+ expect(
+ result.data.publicImports?.unchecked.map(u => u.reason).join('\n'),
+ ).toContain('"types/augment.d.ts"');
+ });
+
+ it('lists a name as not checked whenever any file in the package augments a module, even one nothing loads', async () => {
+ write('dist/augment.d.ts', AUGMENT);
+ write('dist/widget.d.ts', LISTED);
+ write('templates/account-card.tsx', template('AcmeWidget, AcmeWidgetSize'));
+ const result = await validateIntegration(undefined, {cwd: dir});
+ expect(await codes()).toEqual([]);
+ expect(result.data.publicImports?.unchecked).toEqual([
+ expect.objectContaining({
+ specifier: '@acme/widgets/widget',
+ reason: expect.stringContaining('"dist/augment.d.ts"'),
+ }),
+ ]);
+ });
+
+ it('lists a name as not checked when the module re-exports from the augmenting file', async () => {
+ write('dist/augment.d.ts', AUGMENT);
+ write(
+ 'dist/widget.d.ts',
+ `${LISTED}export {AcmeWidgetTone} from './augment.js';\n`,
+ );
+ write('templates/account-card.tsx', template('AcmeWidget, AcmeWidgetSize'));
+ const result = await validateIntegration(undefined, {cwd: dir});
+ expect(await codes()).toEqual([]);
+ expect(
+ result.data.publicImports?.unchecked.map(u => u.reason).join('\n'),
+ ).toContain('"dist/augment.d.ts"');
+ });
+
+ it('lists a name as not checked when the augmentation is reached through another declaration file', async () => {
+ write('dist/augment.d.ts', AUGMENT);
+ write(
+ 'dist/types.d.ts',
+ "import './augment.js';\nexport type AcmeTone = 'a';\n",
+ );
+ write(
+ 'dist/widget.d.ts',
+ "import type {AcmeTone} from './types.js';\ndeclare const AcmeWidget: (t: AcmeTone) => null;\nexport {AcmeWidget};\n",
+ );
+ write('templates/account-card.tsx', template('AcmeWidget, AcmeWidgetSize'));
+ const result = await validateIntegration(undefined, {cwd: dir});
+ expect(await codes()).toEqual([]);
+ expect(
+ result.data.publicImports?.unchecked.map(u => u.reason).join('\n'),
+ ).toContain('"dist/augment.d.ts"');
+ });
+
+ it('lists a name as not checked when TypeScript source augments the module it exports', async () => {
+ pkg(p => {
+ p.exports['./widget'] = './src/widget.ts';
+ });
+ write(
+ 'src/widget.ts',
+ "import './augment.js';\nexport const AcmeWidget = () => null;\n",
+ );
+ write(
+ 'src/augment.ts',
+ "declare module './widget.js' {\n export interface AcmeWidgetSize {\n value: string;\n }\n}\nexport {};\n",
+ );
+ write('templates/account-card.tsx', template('AcmeWidget, AcmeWidgetSize'));
+ const result = await validateIntegration(undefined, {cwd: dir});
+ expect(await codes()).toEqual([]);
+ expect(
+ result.data.publicImports?.unchecked.map(u => u.reason).join('\n'),
+ ).toContain('"src/augment.ts"');
+ });
+
+ it('reads a `.ts` file with an angle-bracket assertion for its augmentation', async () => {
+ write(
+ 'src/augment.ts',
+ "declare const value: unknown;\nconst s = <string>value;\ndeclare module './widget.js' {\n interface AcmeWidgetSize {}\n}\nexport {s};\n",
+ );
+ write('dist/widget.d.ts', LISTED);
+ write('templates/account-card.tsx', template('AcmeWidget, AcmeWidgetSize'));
+ const result = await validateIntegration(undefined, {cwd: dir});
+ expect(await codes()).toEqual([]);
+ expect(result.data.publicImports?.unchecked).toEqual([
+ expect.objectContaining({
+ specifier: '@acme/widgets/widget',
+ reason: expect.stringContaining('"src/augment.ts"'),
+ }),
+ ]);
+ });
+
+ it('counts a file with `declare module` that does not parse as augmenting', async () => {
+ write(
+ 'src/augment.ts',
+ "declare module './widget.js' {\n interface AcmeWidgetSize {\n",
+ );
+ write('dist/widget.d.ts', LISTED);
+ write('templates/account-card.tsx', template('AcmeWidget, AcmeWidgetSize'));
+ const result = await validateIntegration(undefined, {cwd: dir});
+ expect(await codes()).toEqual([]);
+ expect(
+ result.data.publicImports?.unchecked.map(u => u.reason).join('\n'),
+ ).toContain('"src/augment.ts"');
+ });
+
+ it('leaves a declaration file with no import or export (a global script) unchecked', async () => {
+ write(
+ 'dist/widget.d.ts',
+ 'interface AcmeWidgetProps {\n label: string;\n}\ndeclare const AcmeWidget: (p: AcmeWidgetProps) => null;\n',
+ );
+ write(
+ 'templates/account-card.tsx',
+ template('AcmeWidget, AcmeWidgetProps'),
+ );
+ const result = await validateIntegration(undefined, {cwd: dir});
+ expect(await codes()).toEqual([]);
+ expect(result.data.publicImports?.unchecked.map(u => u.specifier)).toEqual([
+ '@acme/widgets/widget',
+ ]);
+ });
+});
+
+describe('declaration files: default exports', () => {
+ const template = (/** @type {string} */ names) =>
+ `import {${names}} from '@acme/widgets/widget';\nexport default function C() {\n return <div />;\n}\n`;
+ const HEAD =
+ 'interface AcmeWidgetProps {\n label: string;\n}\nexport declare const AcmeWidget: (p: AcmeWidgetProps) => null;\n';
+
+ beforeEach(() => {
+ pkg(p => {
+ p.exports['./widget'] = './dist/widget.js';
+ });
+ write('dist/widget.js', 'export const AcmeWidget = () => null;\n');
+ write(
+ 'templates/account-card.tsx',
+ template('AcmeWidget, AcmeWidgetProps'),
+ );
+ });
+
+ for (const [form, tail] of [
+ ['export default function', 'export default function f(): void;\n'],
+ ['export default class', 'export default class K {}\n'],
+ ['export default interface', 'export default interface I {\n a: 1;\n}\n'],
+ ]) {
+ it(`keeps implicit exports after ${form}`, async () => {
+ write('dist/widget.d.ts', HEAD + tail);
+ expect(await codes()).toEqual([]);
+ });
+ }
+
+ for (const [form, tail] of [
+ [
+ 'export default <expression>',
+ 'declare const d: number;\nexport default d;\n',
+ ],
+ ['export {} list', 'export {};\n'],
+ ['export … from', "export {X} from './x';\n"],
+ ['export *', "export * from './x';\n"],
+ ]) {
+ it(`ends implicit exports at ${form}`, async () => {
+ write('dist/widget.d.ts', HEAD + tail);
+ write('dist/x.d.ts', 'export declare const X: number;\n');
+ expect(await codes()).toEqual(['template_import_missing_name']);
+ });
+ }
+});
+
+describe('the default-export fix names a value', () => {
+ it('prefers an exported function or class declaration', async () => {
+ write(
+ 'templates/account-card.tsx',
+ 'export const ACCOUNT_LIMIT = 3;\nexport const Size = "sm";\nexport class AccountCard {}\n',
+ );
+ const [issue] = await found();
+ expect(issue?.message).toContain('export default AccountCard;');
+ });
+
+ it('skips ALL-CAPS names and falls back to the generic fix with none left', async () => {
+ write(
+ 'templates/account-card.tsx',
+ 'export const ACCOUNT_LIMIT = 3;\nexport const API = 1;\n',
+ );
+ const [issue] = await found();
+ expect(issue?.message).not.toContain('export default ACCOUNT_LIMIT');
+ expect(issue?.message).toContain('`export default function …`');
+ });
+
+ it('names no hook, helper or type-only name, and falls back to the generic fix', async () => {
+ write(
+ 'templates/account-card.tsx',
+ 'export function useAccount() {\n return null;\n}\nexport function formatBalance(n: number) {\n return String(n);\n}\nexport const ACCOUNT_LIMIT = 3;\nexport type AccountCardProps = {title: string};\nexport interface AccountCardSize {\n value: string;\n}\n',
+ );
+ const [issue] = await found();
+ expect(issue?.code).toBe('template_no_default_export');
+ expect(issue?.message).not.toContain('export default useAccount;');
+ expect(issue?.message).not.toContain('formatBalance');
+ expect(issue?.message).not.toContain('export default AccountCard');
+ expect(issue?.message).toContain('`export default function …`');
+ });
+
+ it('suggests a PascalCase const when no function or class fits', async () => {
+ write(
+ 'templates/account-card.tsx',
+ 'export function useAccount() {\n return null;\n}\nexport const AccountCard = () => null;\n',
+ );
+ const [issue] = await found();
+ expect(issue?.message).toContain('export default AccountCard;');
+ });
+
+ it('names no public import when package.json has no name', async () => {
+ pkg(p => delete p.name);
+ write(
+ 'templates/account-card.tsx',
+ 'export function AccountCard() {\n return null;\n}\n',
+ );
+ const result = await validateLocalIntegration(dir);
+ const note = (result.notes ?? []).find(
+ n => n.code === 'template_no_default_export',
+ );
+ expect(note?.message).toContain(
+ 'anything that renders the template gets nothing',
+ );
+ expect(note?.message).not.toContain('null/');
+ });
+});
+
+describe('a doc name that differs from its file name', () => {
+ it('leaves the export-name judgment to the doc-name check', async () => {
+ write(
+ 'components/AcmeWidget.doc.mjs',
+ "export default {type: 'component', name: 'AcmeWidgets', import: '@acme/widgets/components/AcmeWidget', usage: {description: 'A widget.'}, props: []};\n",
+ );
+ write(
+ 'components/AcmeWidget.tsx',
+ "export {AcmeWidgets} from '@acme/ui';\n",
+ );
+ const result = await validateIntegration(undefined, {cwd: dir});
+ expect(
+ (await codes()).filter(code => code === 'component_import_missing_name'),
+ ).toEqual([]);
+ expect(
+ (result.data.publicImports?.unchecked ?? []).filter(
+ u => u.file === 'components/AcmeWidget.doc.mjs',
+ ),
+ ).toEqual([]);
+ });
+});