Skip to content

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

TypeScript

feat(cli): integration check lists imports apps cannot use: undeclared exports subpaths, other packages, and template imports outside the root (#7779)

Joey84c7b4f64c3b
diff --git a/.changeset/cli-integration-public-imports.md b/.changeset/cli-integration-public-imports.md
new file mode 100644
index 0000000000..dab20c8979
--- /dev/null
+++ b/.changeset/cli-integration-public-imports.md
@@ -0,0 +1,7 @@
+---
+'@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.
+
+@josephfarina
diff --git a/packages/cli/README.md b/packages/cli/README.md
index e37f810678..d6237460d2 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -470,69 +470,69 @@ Every response has a `type` discriminant. The full set is below (generated from
<!-- BEGIN GENERATED: response-types -->
-| Type | What `data` carries |
-| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `init.run` | The install receipt: the `mode` (`default` \| `features`), the features run, agent-doc files written, any soft `docsError`, whether theme guidance was emitted, the template outcome (`workflow` \| `created` \| `skipped`) plus its path, and whether the next-steps were emitted. |
-| `init.remove` | The removal receipt — returned when --remove-agents is set: `data.removed` is true when a managed agent-docs block was found and removed, and false when there was none to remove. |
-| `init.user` | The computer-level agent text receipt — returned when --user is set: `data.files`, one `{path, action, reason?}` per path acted on, the skill file first and then each link to its folder (action `written` \| `linked` \| `unchanged` \| `removed` \| `absent` \| `kept`; `reason` only on `kept`: `edited` when a person changed the text, `not-astryx` when Astryx did not write it), `data.command` (the command the text names), and `data.warnings`. |
-| `component.list` | The component catalog grouped by component group (each component's group field): `detail` (the level: names \| compact \| full) and `components`, the grouped map of names entries ({name, package, and optional canonical import for integrations}), brief entries ({name, package, description, import}), or a full ComponentDoc per entry with its package. |
-| `component.batch` | The component specialization of the shared `BatchResponse` and `BatchRow` types. An explicit programmatic selector array, or two or more CLI selectors, returns one ordered receipt: `count` plus `results`, one row per selector including duplicates. Every row carries `selector` and `status` (found \| not_found \| ambiguous \| error). A found row carries `result`, the same {type, data} response as one selector. An ambiguous row carries `code`, `error`, and `candidates` ({package, component, kind, installed}). Other failed rows carry `code`, `error`, and optional `suggestions` ({name, reason}). |
-| `component.detail` | One component's authored ComponentDoc plus ownership fields (package, the owner; import, the specifier; sourceAvailable, whether source exists) and parentDoc (present when the component is documented inside another component's doc, naming that doc). The envelope's package names the same owner. |
-| `component.detail.props` | Just one component's props table (ComponentPropDoc[]). The envelope's package names the npm package that owns the component. |
-| `component.detail.source` | One component's source file, as {component, source}. The envelope's package names the npm package that owns the component. |
-| `component.detail.showcase` | One component's showcase example, as {component, aspectRatio, source}. The envelope's package names the npm package that owns the component. |
-| `component.detail.blocks` | One component's example blocks, as {component, showcase, examples, related} of BlockEntry ({name, package, displayName, description, isShowcase, category}); each block names the package that owns it, and the envelope's package names the component's owner. |
-| `docs.list` | All reference-doc topics as DocsListEntry[] ({topic, description, package, replaces?}), in read order; meta.namespaces lists the docs tree's top-level namespaces, and meta.notLoaded each package whose docs did not load. |
-| `docs.detail` | One topic's full ReferenceDoc (the JSON read of a topic, --full, --dense, or a topic with one section), with token-ref blocks inlined and each section naming the package that wrote it, plus links ({up, previous, next}: the commands that open the level it sits in and its neighbors there). |
-| `docs.index` | One topic's section index, the text read of a topic with more than one section (and --index): the topic's name, title, and description, plus sections, each {id, title, package, summary} (pass the id as the section argument; package is the npm package that wrote the section; summary is the section's one-line summary), and links ({up, previous, next}: the commands that open the level it sits in and its neighbors there). |
-| `docs.detail.section` | One ReferenceSection of a topic, found by key or title, with token-ref blocks inlined, plus links ({up, previous, next}: the commands that open its topic index and the sections before and after it). The envelope's package names the npm package that wrote the section. |
-| `docs.node` | One node of the docs tree, read by its route: its id, kind, package, title, summary, and breadcrumb, plus a namespace's slots with their children (one level down, each naming its package) or a typed doc's content, and links ({up, previous, next, related}: the commands that open its parent, its neighbors, and the docs it names). |
-| `blog.list` | The feed URL plus every post parsed from the RSS feed, each with slug, title, description, date, type, authors, link, and plaintext URL. |
-| `blog.detail` | One post's metadata plus the feed URL and the post's full plaintext body. |
-| `discover.list` | What the project has, the integrations it loads and the official packages it declares, official packages first (name, category, components, version, a list per other kind they add, and latest when a source knows it); meta.available lists what the project could add, the official packages first, each with the command that adds it, and meta.sources reports each source, the official list last; when it lists no integration it carries meta.configured to tell "nothing configured" from "nothing discovered". |
-| `discover.detail` | One package, for an @scope/name or @scope/name@version query: what the shown version adds, whether the project has it, and, when a source knows the package, its versions, latest release, and the command that adds it. |
-| `discover.detail.doc` | The validated ComponentDoc for one installed component, for an @scope/name/Component query. |
-| `discover.item` | One item that is not an installed component, for an @scope/name/<item> query: its kind, name, package, version, and whether the project has the package. |
-| `discover.search` | The echoed query plus every matching item and package across all packages, each with its kind and whether the project has it, even when only one matches; total is set when --limit cut the list. |
-| `search` | The echoed query, `matchCount` (total matches, before `limit`), and results, a ranked SearchResultEntry[] bounded by `limit`: each {domain, name, package, score, reason, description, command} (package is the npm package that owns the result), plus import (components, hooks), title, parent (the command that opens the level above), and, for a hit on one section, section (docs), or displayName and kind (templates). When a search with no `type` could not obtain @astryxdesign/core, `meta.partial` is {skipped, reason}: the domains it skipped (component, hook, template) and why. |
-| `build.help` | The how-to-build-a-page playbook, emitted when no query is given: `playbook: true`, a title, the ordered steps (title, commands, optional returns), the on-system rules, and related lookups. Commands are bare subcommands for the caller to render with its own invocation. |
-| `build.kit` | The template to start from and its kit: query, hasResults, matchCount (never a cap), directMatch, start {name, package, command, basis, reason, alternatives, ...} (the start and each alternative name the package that owns the template), pages (search's closest templates), blocks and domain as SearchResultEntry[] (each naming its package), frame and foundation (Core component names), and hint {reason, commands} when thin. |
-| `swizzle.list` | The names of swizzlable components discoverable from cwd's @astryxdesign/core. The envelope's package is @astryxdesign/core. |
-| `swizzle.copy` | An eject receipt: component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and, when the owner has an issues URL, feedback ({issuesUrl, ghCommand?}): where to report the gap that led to swizzling. The envelope's package names the same owning package. |
-| `gap-report.categories` | The fixed gap category values and human-readable labels; when a loaded integration names its own issues URL, meta.destinations lists every destination ({to, default, issuesUrl}) and meta.ask tells an agent to ask the person. |
-| `gap-report.file` | An aggregate receipt: overall status, the selected package, issuesUrl (or null), deliveries in handler order, each {handlerType: project \| integration \| fallback, handler, audience, status, url, message}, and filedCount/routedOnlyCount totals; without --to, when a loaded integration names its own issues URL, destinations and ask as on gap-report.categories. |
-| `template.list` | The effective discovered TemplateListEntry[] for pages and blocks. A winning replacement entry includes optional `replaces`, naming the Core id omitted from the default list. |
-| `template.show` | The resolved template's source, exactly as a copy writes it, plus its description, kind, the component names it composes, and demoMediaReplaced (how many Astryx demo media references were replaced with placeholders for you to swap for your own media). |
-| `template.skeleton` | A layout skeleton (structural tags with spatial annotations) plus the template's description and the components it composes. The envelope's package names the npm package that owns the template. |
-| `template.copy` | A scaffold receipt: template id, output directory, written file name, file count, demoMediaReplaced (how many Astryx demo media references were replaced with placeholders), notes (setup notes naming what the template needs that the project lacks — missing packages, missing StyleX compiler; empty when satisfied), missingPackages (external package names the template imports that are not in the project), and installCommand (a ready-to-run install command with the detected package manager and workspace version ranges; null when nothing is missing, or when several lockfiles leave the package manager undetermined). The envelope's package names the npm package that owns the template. |
-| `template.cdn` | A write receipt for the no-build-step CDN starter page: the path (relative to cwd), the Astryx version every CDN URL was pinned to, whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |
-| `hook.list` | The hook catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of hook names, brief entries, or a full HookDoc per entry. The envelope's package is @astryxdesign/core, the only package that ships hooks. |
-| `hook.detail` | One hook's full authored HookDoc. The envelope's package is @astryxdesign/core. |
-| `hook.detail.params` | Just one hook's parameters table (HookParamDoc[]). The envelope's package is @astryxdesign/core. |
-| `theme.build` | A theme build receipt: name, tokenCount and componentCount (override counts), sizeKB, the written outputs {css, cssDts, js, dts, and variantsDts when applicable}, warnings (defects to fix), and notices (advisories about a correct theme, such as a named font it does not load). |
-| `theme.build.check` | The --check receipt: theme name, an upToDate flag, the stale outputs (each {path, reason: missing \| outdated}), and the full list of checked paths. Writes nothing. |
-| `theme.build.batch` | Several themes built in one invocation: `count` plus one {file, receipt} per theme in argument order, where receipt is that theme's theme.build (or theme.build.check) envelope, or null when it produced no CSS. |
-| `theme.list` | Every bundled, installed package, and local theme as a ThemeListEntry[]. Each entry has slug, displayName, description, maintained, owner package or local root, source, added, and default fields. Optional meta.unmigratedCopies names earlier descriptor-less copies, their missing descriptor, and the upgrade command; those copies are not data entries. |
-| `theme.app` | The app theme record after add, remove, or use. It includes every added theme and its built imports, the default slug, generated module path, and the command change. After add, the envelope package names the npm package that owns the added theme; a local theme has none. |
-| `theme.eject` | A local source-fork receipt with the resolved slug, displayName, source theme maintained flag, source-selector package, outputDir, source entry, exportName, and every file written, including the descriptor. The written local descriptor always uses maintained: false. |
-| `theme.template` | A write receipt for the annotated theme template: the path (relative to cwd), whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |
-| `theme.targets` | The whole themeable surface: the echoed filter, componentCount, and targets, one per theming target — {key, className, component, props, states}, where props and states are its legal override keys. |
-| `theme.palette.generate` | An author-reviewable OKLCH palette candidate, its reproducibility receipt, summary counts, and optional candidate/receipt file-write result. |
-| `upgrade.list` | Every available codemod, oldest→newest, as {name, package, title, version, optional}; returned for --list without running anything. |
-| `upgrade.registry` | The copied-composition receipt for --registry: applied, ok, the counts (found, current, wouldUpdate, updated, wouldMerge, merged, wouldRefreshReceipt, receiptsRefreshed, conflicts, missing, invalid, failed), and items. |
-| `upgrade.status` | A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. no_codemods and config_fixable carry cliBehindCore ({cliVersion, command}) when the installed Core is newer than the CLI, which then has no codemods for the releases after its own version. |
-| `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, sourcePathFound (false when the resolved source directory does not exist, so no source file was read), and (apply mode) filesChanged, transformsApplied, and per-codemod errors. When the installed Core is newer than the CLI, it also carries cliBehindCore ({cliVersion, command}): codemods for the releases after cliVersion did not run. |
-| `manifest` | The CLI capability manifest: name, version, apiVersion, description, globalOptions, commands (each name, description, arguments, options, json, aliases?, responseTypes?, examples?, exitCodes? as [{code, when}], outsideProject? (same, refuse, or own; absent on a group), subcommands?), jsonSupported, globalMode ({docs, summary}: what a run may do beyond its command, such as the hand-off to the project's own CLI, the daily update check, and the agent skill file, and the docs topic that explains it), and the flat responseTypes index. |
-| `help` | Help, in one of two shapes. A bare `astryx --json` returns the root manifest: name, version, commands (the command names), jsonSupported, and manifest (the full payload `astryx manifest --json` returns). `--help --json` on any command, or `astryx help [command] --json`, returns that command's help: command, description, usage, options (each flags, description, and defaultValue and choices when set), and subcommands (each name and description). data.manifest marks the first shape; data.usage marks the second. |
-| `version` | The CLI version, for `astryx --version --json`: {version}. |
-| `doctor` | The health-check report: `checks` (each with id, label, status: pass \| warn \| fail \| info, a message, and an optional fix, always present on warn and fail) plus a `summary` of counts per status. |
-| `integration.add` | A contribution-writer receipt: kind, name, optional root {path, created}, integration-manifest path, every affected project-relative path, written, and dryRun. |
-| `integration.pack-check` | The packed-package check: name, version, packable, tarball {filename, fileCount, size, unpackedSize} or null, inventory {manifest, roots [{kind, path, expectedFiles, missingFiles, complete}], expectedFiles, packedFiles}, contributions {local, packed}, each null or {themes [{slug, exportName}], components, templates [{id, type, name}], codemods [{version, id}], docs, agentDocsAppend}, and issues [{code, severity, message, fix?, file?, line?}] (the issues validation finds in the source and, prefixed packed_, in the packed tree, with the fix and the place when the check knows them). |
-| `integration.validate` | The validation result: validated (false when nothing was validated: with no package.json the issues list carries one no_package error so the command exits 1, and with a package.json but no integration manifest the issues list is empty and proves nothing), the package name and version (both null when validated is false) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning \| error, message, fix?, file?, line?} (fix: the change that resolves it; file and line: where, relative to the package), and notes when there are any: {code, message} information that fails nothing, such as invalid_cli_command for a malformed cliCommand, 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_provider_id, source_without_component_doc where a doc and its source still pair), and doc_name_mismatch and unknown_block_component, until they become warnings in the next minor release. A runner_command note lists each Astryx command a topic writes with a package runner (its file, line and the bare command to write). When the manifest loads, docTypes checks each doc against its published authoring type: status (checked \| skipped), reason, typescript, docs, findings (all warnings, each naming the field and a fix), unchecked, and fixtures (test fixture docs not checked). When the manifest loads, 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, 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). |
-| `integration.template-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking Core template-id conflicts as {id, severity: warning, integrationPackage, integrationType, integrationName, coreMatches, message, command}. |
-| `integration.component-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking conflicts where an integration component name is also owned by Core; each conflict includes the exact package-qualified command. When the manifest loads and declares a components root, propDrift compares documented props with the TypeScript props: status (checked \| skipped), reason, typescript, components, typesCompared, typesSkipped, findings (all warnings; a default_mismatch carries docDefault, codeDefault, and a fix), unchecked, typesNotCompared, and propsNotChecked. |
-| `integration.doc-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and Core doc overlaps. Each finding includes `severity` (`info` \| `error`) and `relationship` (`replaces` \| `extends` \| `accidental`). copiedPassages lists each pair of topics that repeat 10 or more words of prose word for word: topic, section, otherTopic, otherOwner (package \| core), words, passages, owner (the topic that should keep the text), text (the passage as the topic writes it), line (where the copy starts in the topic to change, or null), and message (the exact replacement); each is also a copied_passage warning in issues. fluff lists padding phrases and low-density topics: topic, kind (phrase \| density), phrase, section, file (relative to the package root), line, density, and message (what to cut or write instead); each is also a doc_fluff warning in issues. strayPointers lists each code span that is exactly `astryx docs <name>` for a doc that exists, in the prose, description or summary of a topic or the text fields of a component doc: topic (the topic or component doc), kind (topic \| component), section, field (the field outside any section, such as description or usage.bestPractices[0].description, else null), file (relative to the package root), line, pointer (the written command), link (the {@link} that replaces it), and message; each is also a stray_doc_pointer warning in issues. |
-| `integration.check` | Every source check of an integration package in one result: validated (false when no integration manifest was found, so nothing was checked), the package name and version, strict, and checks, one entry per check (validate, components, templates, docs), each with check, errors, warnings, skipped, failed, and response, the envelope that check returns on its own. The totals are errors, warnings, and skipped; unchecked counts what the checks could not compare. With --strict, failures lists each warning and each piece of skipped work again as an error, in the issue format the checks use; it is empty without --strict. failed decides the exit code. |
+| Type | What `data` carries |
+| --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `init.run` | The install receipt: the `mode` (`default` \| `features`), the features run, agent-doc files written, any soft `docsError`, whether theme guidance was emitted, the template outcome (`workflow` \| `created` \| `skipped`) plus its path, and whether the next-steps were emitted. |
+| `init.remove` | The removal receipt — returned when --remove-agents is set: `data.removed` is true when a managed agent-docs block was found and removed, and false when there was none to remove. |
+| `init.user` | The computer-level agent text receipt — returned when --user is set: `data.files`, one `{path, action, reason?}` per path acted on, the skill file first and then each link to its folder (action `written` \| `linked` \| `unchanged` \| `removed` \| `absent` \| `kept`; `reason` only on `kept`: `edited` when a person changed the text, `not-astryx` when Astryx did not write it), `data.command` (the command the text names), and `data.warnings`. |
+| `component.list` | The component catalog grouped by component group (each component's group field): `detail` (the level: names \| compact \| full) and `components`, the grouped map of names entries ({name, package, and optional canonical import for integrations}), brief entries ({name, package, description, import}), or a full ComponentDoc per entry with its package. |
+| `component.batch` | The component specialization of the shared `BatchResponse` and `BatchRow` types. An explicit programmatic selector array, or two or more CLI selectors, returns one ordered receipt: `count` plus `results`, one row per selector including duplicates. Every row carries `selector` and `status` (found \| not_found \| ambiguous \| error). A found row carries `result`, the same {type, data} response as one selector. An ambiguous row carries `code`, `error`, and `candidates` ({package, component, kind, installed}). Other failed rows carry `code`, `error`, and optional `suggestions` ({name, reason}). |
+| `component.detail` | One component's authored ComponentDoc plus ownership fields (package, the owner; import, the specifier; sourceAvailable, whether source exists) and parentDoc (present when the component is documented inside another component's doc, naming that doc). The envelope's package names the same owner. |
+| `component.detail.props` | Just one component's props table (ComponentPropDoc[]). The envelope's package names the npm package that owns the component. |
+| `component.detail.source` | One component's source file, as {component, source}. The envelope's package names the npm package that owns the component. |
+| `component.detail.showcase` | One component's showcase example, as {component, aspectRatio, source}. The envelope's package names the npm package that owns the component. |
+| `component.detail.blocks` | One component's example blocks, as {component, showcase, examples, related} of BlockEntry ({name, package, displayName, description, isShowcase, category}); each block names the package that owns it, and the envelope's package names the component's owner. |
+| `docs.list` | All reference-doc topics as DocsListEntry[] ({topic, description, package, replaces?}), in read order; meta.namespaces lists the docs tree's top-level namespaces, and meta.notLoaded each package whose docs did not load. |
+| `docs.detail` | One topic's full ReferenceDoc (the JSON read of a topic, --full, --dense, or a topic with one section), with token-ref blocks inlined and each section naming the package that wrote it, plus links ({up, previous, next}: the commands that open the level it sits in and its neighbors there). |
+| `docs.index` | One topic's section index, the text read of a topic with more than one section (and --index): the topic's name, title, and description, plus sections, each {id, title, package, summary} (pass the id as the section argument; package is the npm package that wrote the section; summary is the section's one-line summary), and links ({up, previous, next}: the commands that open the level it sits in and its neighbors there). |
+| `docs.detail.section` | One ReferenceSection of a topic, found by key or title, with token-ref blocks inlined, plus links ({up, previous, next}: the commands that open its topic index and the sections before and after it). The envelope's package names the npm package that wrote the section. |
+| `docs.node` | One node of the docs tree, read by its route: its id, kind, package, title, summary, and breadcrumb, plus a namespace's slots with their children (one level down, each naming its package) or a typed doc's content, and links ({up, previous, next, related}: the commands that open its parent, its neighbors, and the docs it names). |
+| `blog.list` | The feed URL plus every post parsed from the RSS feed, each with slug, title, description, date, type, authors, link, and plaintext URL. |
+| `blog.detail` | One post's metadata plus the feed URL and the post's full plaintext body. |
+| `discover.list` | What the project has, the integrations it loads and the official packages it declares, official packages first (name, category, components, version, a list per other kind they add, and latest when a source knows it); meta.available lists what the project could add, the official packages first, each with the command that adds it, and meta.sources reports each source, the official list last; when it lists no integration it carries meta.configured to tell "nothing configured" from "nothing discovered". |
+| `discover.detail` | One package, for an @scope/name or @scope/name@version query: what the shown version adds, whether the project has it, and, when a source knows the package, its versions, latest release, and the command that adds it. |
+| `discover.detail.doc` | The validated ComponentDoc for one installed component, for an @scope/name/Component query. |
+| `discover.item` | One item that is not an installed component, for an @scope/name/<item> query: its kind, name, package, version, and whether the project has the package. |
+| `discover.search` | The echoed query plus every matching item and package across all packages, each with its kind and whether the project has it, even when only one matches; total is set when --limit cut the list. |
+| `search` | The echoed query, `matchCount` (total matches, before `limit`), and results, a ranked SearchResultEntry[] bounded by `limit`: each {domain, name, package, score, reason, description, command} (package is the npm package that owns the result), plus import (components, hooks), title, parent (the command that opens the level above), and, for a hit on one section, section (docs), or displayName and kind (templates). When a search with no `type` could not obtain @astryxdesign/core, `meta.partial` is {skipped, reason}: the domains it skipped (component, hook, template) and why. |
+| `build.help` | The how-to-build-a-page playbook, emitted when no query is given: `playbook: true`, a title, the ordered steps (title, commands, optional returns), the on-system rules, and related lookups. Commands are bare subcommands for the caller to render with its own invocation. |
+| `build.kit` | The template to start from and its kit: query, hasResults, matchCount (never a cap), directMatch, start {name, package, command, basis, reason, alternatives, ...} (the start and each alternative name the package that owns the template), pages (search's closest templates), blocks and domain as SearchResultEntry[] (each naming its package), frame and foundation (Core component names), and hint {reason, commands} when thin. |
+| `swizzle.list` | The names of swizzlable components discoverable from cwd's @astryxdesign/core. The envelope's package is @astryxdesign/core. |
+| `swizzle.copy` | An eject receipt: component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and, when the owner has an issues URL, feedback ({issuesUrl, ghCommand?}): where to report the gap that led to swizzling. The envelope's package names the same owning package. |
+| `gap-report.categories` | The fixed gap category values and human-readable labels; when a loaded integration names its own issues URL, meta.destinations lists every destination ({to, default, issuesUrl}) and meta.ask tells an agent to ask the person. |
+| `gap-report.file` | An aggregate receipt: overall status, the selected package, issuesUrl (or null), deliveries in handler order, each {handlerType: project \| integration \| fallback, handler, audience, status, url, message}, and filedCount/routedOnlyCount totals; without --to, when a loaded integration names its own issues URL, destinations and ask as on gap-report.categories. |
+| `template.list` | The effective discovered TemplateListEntry[] for pages and blocks. A winning replacement entry includes optional `replaces`, naming the Core id omitted from the default list. |
+| `template.show` | The resolved template's source, exactly as a copy writes it, plus its description, kind, the component names it composes, and demoMediaReplaced (how many Astryx demo media references were replaced with placeholders for you to swap for your own media). |
+| `template.skeleton` | A layout skeleton (structural tags with spatial annotations) plus the template's description and the components it composes. The envelope's package names the npm package that owns the template. |
+| `template.copy` | A scaffold receipt: template id, output directory, written file name, file count, demoMediaReplaced (how many Astryx demo media references were replaced with placeholders), notes (setup notes naming what the template needs that the project lacks — missing packages, missing StyleX compiler; empty when satisfied), missingPackages (external package names the template imports that are not in the project), and installCommand (a ready-to-run install command with the detected package manager and workspace version ranges; null when nothing is missing, or when several lockfiles leave the package manager undetermined). The envelope's package names the npm package that owns the template. |
+| `template.cdn` | A write receipt for the no-build-step CDN starter page: the path (relative to cwd), the Astryx version every CDN URL was pinned to, whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |
+| `hook.list` | The hook catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of hook names, brief entries, or a full HookDoc per entry. The envelope's package is @astryxdesign/core, the only package that ships hooks. |
+| `hook.detail` | One hook's full authored HookDoc. The envelope's package is @astryxdesign/core. |
+| `hook.detail.params` | Just one hook's parameters table (HookParamDoc[]). The envelope's package is @astryxdesign/core. |
+| `theme.build` | A theme build receipt: name, tokenCount and componentCount (override counts), sizeKB, the written outputs {css, cssDts, js, dts, and variantsDts when applicable}, warnings (defects to fix), and notices (advisories about a correct theme, such as a named font it does not load). |
+| `theme.build.check` | The --check receipt: theme name, an upToDate flag, the stale outputs (each {path, reason: missing \| outdated}), and the full list of checked paths. Writes nothing. |
+| `theme.build.batch` | Several themes built in one invocation: `count` plus one {file, receipt} per theme in argument order, where receipt is that theme's theme.build (or theme.build.check) envelope, or null when it produced no CSS. |
+| `theme.list` | Every bundled, installed package, and local theme as a ThemeListEntry[]. Each entry has slug, displayName, description, maintained, owner package or local root, source, added, and default fields. Optional meta.unmigratedCopies names earlier descriptor-less copies, their missing descriptor, and the upgrade command; those copies are not data entries. |
+| `theme.app` | The app theme record after add, remove, or use. It includes every added theme and its built imports, the default slug, generated module path, and the command change. After add, the envelope package names the npm package that owns the added theme; a local theme has none. |
+| `theme.eject` | A local source-fork receipt with the resolved slug, displayName, source theme maintained flag, source-selector package, outputDir, source entry, exportName, and every file written, including the descriptor. The written local descriptor always uses maintained: false. |
+| `theme.template` | A write receipt for the annotated theme template: the path (relative to cwd), whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |
+| `theme.targets` | The whole themeable surface: the echoed filter, componentCount, and targets, one per theming target — {key, className, component, props, states}, where props and states are its legal override keys. |
+| `theme.palette.generate` | An author-reviewable OKLCH palette candidate, its reproducibility receipt, summary counts, and optional candidate/receipt file-write result. |
+| `upgrade.list` | Every available codemod, oldest→newest, as {name, package, title, version, optional}; returned for --list without running anything. |
+| `upgrade.registry` | The copied-composition receipt for --registry: applied, ok, the counts (found, current, wouldUpdate, updated, wouldMerge, merged, wouldRefreshReceipt, receiptsRefreshed, conflicts, missing, invalid, failed), and items. |
+| `upgrade.status` | A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. no_codemods and config_fixable carry cliBehindCore ({cliVersion, command}) when the installed Core is newer than the CLI, which then has no codemods for the releases after its own version. |
+| `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, sourcePathFound (false when the resolved source directory does not exist, so no source file was read), and (apply mode) filesChanged, transformsApplied, and per-codemod errors. When the installed Core is newer than the CLI, it also carries cliBehindCore ({cliVersion, command}): codemods for the releases after cliVersion did not run. |
+| `manifest` | The CLI capability manifest: name, version, apiVersion, description, globalOptions, commands (each name, description, arguments, options, json, aliases?, responseTypes?, examples?, exitCodes? as [{code, when}], outsideProject? (same, refuse, or own; absent on a group), subcommands?), jsonSupported, globalMode ({docs, summary}: what a run may do beyond its command, such as the hand-off to the project's own CLI, the daily update check, and the agent skill file, and the docs topic that explains it), and the flat responseTypes index. |
+| `help` | Help, in one of two shapes. A bare `astryx --json` returns the root manifest: name, version, commands (the command names), jsonSupported, and manifest (the full payload `astryx manifest --json` returns). `--help --json` on any command, or `astryx help [command] --json`, returns that command's help: command, description, usage, options (each flags, description, and defaultValue and choices when set), and subcommands (each name and description). data.manifest marks the first shape; data.usage marks the second. |
+| `version` | The CLI version, for `astryx --version --json`: {version}. |
+| `doctor` | The health-check report: `checks` (each with id, label, status: pass \| warn \| fail \| info, a message, and an optional fix, always present on warn and fail) plus a `summary` of counts per status. |
+| `integration.add` | A contribution-writer receipt: kind, name, optional root {path, created}, integration-manifest path, every affected project-relative path, written, and dryRun. |
+| `integration.pack-check` | The packed-package check: name, version, packable, tarball {filename, fileCount, size, unpackedSize} or null, inventory {manifest, roots [{kind, path, expectedFiles, missingFiles, complete}], expectedFiles, packedFiles}, contributions {local, packed}, each null or {themes [{slug, exportName}], components, templates [{id, type, name}], codemods [{version, id}], docs, agentDocsAppend}, and issues [{code, severity, message, fix?, file?, line?}] (the issues validation finds in the source and, prefixed packed_, in the packed tree, with the fix and the place when the check knows them). |
+| `integration.validate` | The validation result: validated (false when nothing was validated: with no package.json the issues list carries one no_package error so the command exits 1, and with a package.json but no integration manifest the issues list is empty and proves nothing), the package name and version (both null when validated is false) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning \| error, message, fix?, file?, line?} (fix: the change that resolves it; file and line: where, relative to the package), and notes when there are any: {code, message} information that fails nothing, such as invalid_cli_command for a malformed cliCommand, 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_provider_id, source_without_component_doc where a doc and its source still pair), and doc_name_mismatch and unknown_block_component, until they become warnings in the next minor release. A runner_command note lists each Astryx command a topic writes with a package runner (its file, line and the bare command to write). When the manifest loads, docTypes checks each doc against its published authoring type: status (checked \| skipped), reason, typescript, docs, findings (all warnings, each naming the field and a fix), unchecked, and fixtures (test fixture docs not checked). When the manifest loads, 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, 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 also a note (its fix in the message), listed only and failing --strict from the next minor. publicImports ({status: checked, findings: [], unchecked}) lists each import the check could not judge as {file, specifier, reason}; never counted or failed on. |
+| `integration.template-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking Core template-id conflicts as {id, severity: warning, integrationPackage, integrationType, integrationName, coreMatches, message, command}. |
+| `integration.component-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking conflicts where an integration component name is also owned by Core; each conflict includes the exact package-qualified command. When the manifest loads and declares a components root, propDrift compares documented props with the TypeScript props: status (checked \| skipped), reason, typescript, components, typesCompared, typesSkipped, findings (all warnings; a default_mismatch carries docDefault, codeDefault, and a fix), unchecked, typesNotCompared, and propsNotChecked. |
+| `integration.doc-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and Core doc overlaps. Each finding includes `severity` (`info` \| `error`) and `relationship` (`replaces` \| `extends` \| `accidental`). copiedPassages lists each pair of topics that repeat 10 or more words of prose word for word: topic, section, otherTopic, otherOwner (package \| core), words, passages, owner (the topic that should keep the text), text (the passage as the topic writes it), line (where the copy starts in the topic to change, or null), and message (the exact replacement); each is also a copied_passage warning in issues. fluff lists padding phrases and low-density topics: topic, kind (phrase \| density), phrase, section, file (relative to the package root), line, density, and message (what to cut or write instead); each is also a doc_fluff warning in issues. strayPointers lists each code span that is exactly `astryx docs <name>` for a doc that exists, in the prose, description or summary of a topic or the text fields of a component doc: topic (the topic or component doc), kind (topic \| component), section, field (the field outside any section, such as description or usage.bestPractices[0].description, else null), file (relative to the package root), line, pointer (the written command), link (the {@link} that replaces it), and message; each is also a stray_doc_pointer warning in issues. |
+| `integration.check` | Every source check of an integration package in one result: validated (false when no integration manifest was found, so nothing was checked), the package name and version, strict, and checks, one entry per check (validate, components, templates, docs), each with check, errors, warnings, skipped, failed, and response, the envelope that check returns on its own. The totals are errors, warnings, and skipped; unchecked counts what the checks could not compare. With --strict, failures lists each warning and each piece of skipped work again as an error, in the issue format the checks use; it is empty without --strict. failed decides the exit code. |
<!-- END GENERATED: response-types -->
<!-- Generated by scripts/generate-cli-readme.mjs from the response-types EnumDoc. Run `pnpm -F @astryxdesign/cli readme`. -->
diff --git a/packages/cli/api/component/component-replacement.test.mjs b/packages/cli/api/component/component-replacement.test.mjs
index d4bf384f42..284cdb102b 100644
--- a/packages/cli/api/component/component-replacement.test.mjs
+++ b/packages/cli/api/component/component-replacement.test.mjs
@@ -64,6 +64,7 @@ function writeIntegration(name, components, peers) {
type: 'component',
name: componentName,
displayName: componentName,
+ import: `${name}/components/${componentName}`,
...(replaces ? {replaces} : {}),
keywords: ['acme'],
usage: {description: `${componentName} for Acme apps.`},
diff --git a/packages/cli/api/integration/validate-integration-fixes.test.mjs b/packages/cli/api/integration/validate-integration-fixes.test.mjs
index ce7b15fabd..edd2fe7f63 100644
--- a/packages/cli/api/integration/validate-integration-fixes.test.mjs
+++ b/packages/cli/api/integration/validate-integration-fixes.test.mjs
@@ -37,6 +37,7 @@ const componentDoc = name =>
`export default {type: 'component', name: '${name}', displayName: '${name}', usage: {description: '${name}.'}, props: []};\n`;
/** @param {string} name */
const componentSource = name => `export function ${name}() { return null; }\n`;
+/** @param {string} name */
const templateSource = name =>
`export default function ${name}() { return null; }\n`;
/** @param {string} name */
@@ -398,9 +399,9 @@ describe('unreachable_contribution fixes hold when followed', () => {
const dir = writePackage({
[MANIFEST]: manifest({templates: './templates'}),
'templates/hero.doc.mjs': `export default {type: 'page', name: 'hero', displayName: 'Hero'};\n`,
- 'templates/hero.tsx': componentSource('Hero'),
+ 'templates/hero.tsx': templateSource('Hero'),
'src/blocks/Carousel.doc.mjs': `export default {type: 'block', name: 'Carousel', displayName: 'Carousel', aspectRatio: 1};\n`,
- 'src/blocks/Carousel.tsx': componentSource('Carousel'),
+ 'src/blocks/Carousel.tsx': templateSource('Carousel'),
});
const message = only(await issuesOf(dir), 'unreachable_contribution');
@@ -423,7 +424,7 @@ describe('unreachable_contribution fixes hold when followed', () => {
[MANIFEST]: manifest({templates: './templates'}),
'templates/.keep': '',
'src/blocks/Carousel.doc.mjs': `export default {type: 'block', name: 'Carousel', displayName: 'Carousel', aspectRatio: 1};\n`,
- 'src/blocks/Carousel.tsx': componentSource('Carousel'),
+ 'src/blocks/Carousel.tsx': templateSource('Carousel'),
});
const message = only(await issuesOf(dir), 'unreachable_contribution');
@@ -687,9 +688,9 @@ describe('fixes never move a contribution onto a name its root already has', ()
const dir = writePackage({
[MANIFEST]: manifest({templates: './templates'}),
'templates/hero.doc.mjs': `export default {type: 'page', name: 'hero', displayName: 'Hero'};\n`,
- 'templates/hero.tsx': componentSource('Hero'),
+ 'templates/hero.tsx': templateSource('Hero'),
'extra/hero.doc.mjs': `export default {type: 'page', name: 'hero', displayName: 'Hero'};\n`,
- 'extra/hero.tsx': componentSource('Hero'),
+ 'extra/hero.tsx': templateSource('Hero'),
});
const message = only(await issuesOf(dir), 'unreachable_contribution');
diff --git a/packages/cli/api/integration/validate-integration-gaps.test.mjs b/packages/cli/api/integration/validate-integration-gaps.test.mjs
index fc1922d938..b649c106ac 100644
--- a/packages/cli/api/integration/validate-integration-gaps.test.mjs
+++ b/packages/cli/api/integration/validate-integration-gaps.test.mjs
@@ -169,6 +169,7 @@ const writeNamed = files =>
version: '1.0.0',
exports: {
'./components/*': './components/*.tsx',
+ './templates/*': './templates/*.tsx',
'.': './index.ts',
},
});
@@ -534,7 +535,14 @@ describe('block component names', () => {
'export function Panel() { return null; }\nexport const UI = {};\nexport const Lib = {};\nexport function pick() { return null; }\n',
...files,
},
- {name: '@acme/kit', version: '1.0.0', exports: {'.': './index.tsx'}},
+ {
+ name: '@acme/kit',
+ version: '1.0.0',
+ exports: {
+ '.': './index.tsx',
+ './templates/*': './templates/*.tsx',
+ },
+ },
);
/** @param {string} extra */
const block = extra =>
diff --git a/packages/cli/api/integration/validate-integration.mjs b/packages/cli/api/integration/validate-integration.mjs
index f079a5362a..74a267de2c 100644
--- a/packages/cli/api/integration/validate-integration.mjs
+++ b/packages/cli/api/integration/validate-integration.mjs
@@ -70,6 +70,7 @@ import {
rootProblem,
} from '../../foundation/integrations/validate-contributions.mjs';
import {formatCliCommand} from '../../foundation/env/package-manager.mjs';
+import {publicImportIssues} from '../../foundation/integrations/public-imports.mjs';
export {validateLoadedIntegration, isListedIssue};
@@ -92,6 +93,8 @@ export {validateLoadedIntegration, isListedIssue};
* may not fail `--strict` until the next (architecture:cli-surface INV35);
* `integration verify` still fails on a package.json npm cannot pack.
* @property {import('../../foundation/integrations/integrations.mjs').LoadedIntegration} [integration]
+ * @property {import('./validate-integration.type.mjs').PublicImportsReport} [publicImports]
+ * what the public-import check could not judge
*/
/**
@@ -444,6 +447,14 @@ async function validateAtPackageDir(
packageDir,
)),
);
+ // What the package tells apps to import, read from source: package.json
+ // `exports`, docs, examples and template imports.
+ const publicImports = await publicImportIssues(packageDir, loaded);
+ issues.push(...publicImports.issues);
+ // Each finding is a note until the next minor makes it a warning.
+ if (publicImports.notes.length > 0)
+ (result.notes ??= []).push(...publicImports.notes);
+ result.publicImports = publicImports.report;
if (scanUnreachable) {
issues.push(
...(await findUnreachableContributionIssues(
@@ -744,6 +755,10 @@ export async function validateIntegration(pkg, options = {}) {
...(docTypes ? {docTypes} : {}),
...(docNames ? {docNames} : {}),
...(blockComponents ? {blockComponents} : {}),
+ // What the public-import check could not judge: listed, never failed on.
+ ...(result.found && result.publicImports
+ ? {publicImports: result.publicImports}
+ : {}),
},
};
}
diff --git a/packages/cli/api/integration/validate-integration.type.mjs b/packages/cli/api/integration/validate-integration.type.mjs
index d70ac53411..de1fb9b0af 100644
--- a/packages/cli/api/integration/validate-integration.type.mjs
+++ b/packages/cli/api/integration/validate-integration.type.mjs
@@ -39,7 +39,7 @@
* "healthy" — the two are otherwise byte-identical.
* @typedef {object} ValidateIntegrationResponse
* @property {'integration.validate'} type
- * @property {{validated: boolean, name: string | null, version: string | null, issues: import('../../foundation/integrations/issue').AstryxIntegrationIssue[], notes?: Array<{code: string, message: string}>, docTypes?: DocTypesReport, docNames?: DocNamesReport, blockComponents?: BlockComponentsReport}} data
+ * @property {{validated: boolean, name: string | null, version: string | null, issues: import('../../foundation/integrations/issue').AstryxIntegrationIssue[], notes?: Array<{code: string, message: string}>, docTypes?: DocTypesReport, docNames?: DocNamesReport, blockComponents?: BlockComponentsReport, publicImports?: PublicImportsReport}} data
* `notes`: information beside the issues that fails nothing, such as
* `invalid_cli_command`, a `cliCommand` that was ignored as malformed, and
* the package layout findings added after the last minor release, each with
@@ -49,10 +49,11 @@
* (`unreadable_file`), a package.json without `name` or `version`
* (`invalid_package_json`), no provider ID (`no_provider_id`), and a doc
* whose file name differs from its source only in letter case where the two
- * still pair (`source_without_component_doc`); and `doc_name_mismatch` and
- * `unknown_block_component` (see `docNames` and `blockComponents`); they
- * become warnings in the next minor release; and `runner_command`, an
- * Astryx command a topic writes with a package runner
+ * still pair (`source_without_component_doc`); `doc_name_mismatch` and
+ * `unknown_block_component` (see `docNames` and `blockComponents`); and
+ * since 0.7.3 each public-import finding; they become warnings in the next
+ * minor release; and `runner_command`, an Astryx command a topic writes
+ * with a package runner
*/
/**
@@ -99,3 +100,21 @@
*/
export {};
+
+/**
+ * An import the public-import check could not judge.
+ * @typedef {object} PublicImportUnchecked
+ * @property {string} file package-relative file that names it
+ * @property {string} specifier the import specifier
+ * @property {string} reason why it was not checked
+ */
+
+/**
+ * The public-import check's report on validate's result: `unchecked` lists
+ * what it could not judge, never counted or failed on. Its findings are
+ * notes on the result (`data.notes`), so `findings` stays empty.
+ * @typedef {object} PublicImportsReport
+ * @property {'checked'} status
+ * @property {never[]} findings
+ * @property {PublicImportUnchecked[]} unchecked
+ */
diff --git a/packages/cli/api/integration/validateIntegration.doc.mjs b/packages/cli/api/integration/validateIntegration.doc.mjs
index 0016dbcc43..3257c94497 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 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).',
+ '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 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.',
},
],
examples: [
diff --git a/packages/cli/assets/docs/tree/checks.doc.mjs b/packages/cli/assets/docs/tree/checks.doc.mjs
index 37c2d0d208..9ff807996e 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`). 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`). 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",
],
[
'`astryx doctor integration components`',
diff --git a/packages/cli/clients/cli/commands/doctor-integration.test.mjs b/packages/cli/clients/cli/commands/doctor-integration.test.mjs
index 0c1f7a8bf3..eaa33fb554 100644
--- a/packages/cli/clients/cli/commands/doctor-integration.test.mjs
+++ b/packages/cli/clients/cli/commands/doctor-integration.test.mjs
@@ -19,7 +19,10 @@ import {Command} from 'commander';
import {discoverCoreTemplates} from '../../../foundation/discovery/template-adapter.mjs';
import {discoverOwnedComponents} from '../../../foundation/discovery/component-discovery.mjs';
import {discoverBuiltinTopics} from '../../../foundation/discovery/docs-discovery.mjs';
-import {findCoreDir, findProjectCoreDir} from '../../../foundation/fs/paths.mjs';
+import {
+ findCoreDir,
+ findProjectCoreDir,
+} from '../../../foundation/fs/paths.mjs';
import {registerDoctor} from './doctor.mjs';
import {expectRecordsCarry} from '../../../test-utils/text-projection.mjs';
@@ -674,6 +677,51 @@ describe('doctor integration — command', () => {
}
});
+ it('validate prints the public-import findings as listed only, and still exits 0', async () => {
+ writeIntegration({id: 'hero', name: 'Hero', type: 'block'});
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: '@acme/widgets', version: '1.2.3', exports: {}}),
+ );
+ process.chdir(tmpDir);
+
+ await createProgram().parseAsync([
+ 'node',
+ 'astryx',
+ 'doctor',
+ 'integration',
+ 'validate',
+ ]);
+
+ const output = logCalls.join('\n');
+ expect(output).toContain('note (template_import_not_exported):');
+ expect(output).toContain('Fix:');
+ expect(output).toContain('[ok] No integration issues found.');
+ expect(process.exitCode).toBeUndefined();
+ });
+
+ it('validate lists, as not checked, the imports it cannot judge when package.json has no name', async () => {
+ writeIntegration({id: 'hero', name: 'Hero', type: 'block'});
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({version: '1.2.3'}),
+ );
+ process.chdir(tmpDir);
+
+ await createProgram().parseAsync([
+ 'node',
+ 'astryx',
+ 'doctor',
+ 'integration',
+ 'validate',
+ ]);
+
+ const output = logCalls.join('\n');
+ expect(output).toMatch(/\[info\] Imports not checked: 1:/);
+ expect(output).toContain('package.json has no "name"');
+ expect(process.exitCode).toBeUndefined();
+ });
+
it('templates warns on a Core id and writes the exact --package command', async () => {
const [core] = await discoverCoreTemplates();
expect(core).toBeDefined();
diff --git a/packages/cli/clients/cli/commands/doctor.mjs b/packages/cli/clients/cli/commands/doctor.mjs
index 27f6327a49..c24cb741e8 100644
--- a/packages/cli/clients/cli/commands/doctor.mjs
+++ b/packages/cli/clients/cli/commands/doctor.mjs
@@ -234,6 +234,16 @@ function printIntegrationValidation(data) {
...docTypesBlocks(data.docTypes, errors > 0),
...docNamesBlocks(data.docNames),
...blockComponentsBlocks(data.blockComponents),
+ ...(data.publicImports && data.publicImports.unchecked.length > 0
+ ? [
+ text(
+ `[info] Imports not checked: ${data.publicImports.unchecked.length}:`,
+ ),
+ records(data.publicImports.unchecked, {
+ fields: ['file', 'specifier', 'reason'],
+ }),
+ ]
+ : []),
);
}
diff --git a/packages/cli/foundation/integrations/exports-subpaths.mjs b/packages/cli/foundation/integrations/exports-subpaths.mjs
new file mode 100644
index 0000000000..5c37bc2be6
--- /dev/null
+++ b/packages/cli/foundation/integrations/exports-subpaths.mjs
@@ -0,0 +1,113 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file How a package.json `exports` field declares a subpath, read without
+ * touching the targets (which may be build output that does not exist yet).
+ *
+ * @input A package.json `exports` value and a `.`/`./…` subpath.
+ * @output Whether the subpath is declared for an ES module importer, and why
+ * not when it is not.
+ * @position foundation/integrations; read by the public-import checks.
+ */
+
+/** @param {unknown} value @returns {value is Record<string, unknown>} */
+export function isRecord(value) {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+/**
+ * Whether an export value gives an ES module importer something: a string,
+ * or a condition object / fallback array with a target under a condition
+ * other than `require` and `types`.
+ * @param {unknown} value
+ * @returns {boolean}
+ */
+export function importable(value) {
+ if (typeof value === 'string') return true;
+ if (Array.isArray(value)) return value.some(importable);
+ if (!isRecord(value)) return false;
+ return Object.entries(value).some(
+ ([condition, target]) =>
+ condition !== 'require' && condition !== 'types' && importable(target),
+ );
+}
+
+/**
+ * Every string target an export value names, any condition.
+ * @param {unknown} value
+ * @param {string[]} [out]
+ * @returns {string[]}
+ */
+export function allTargets(value, out = []) {
+ if (typeof value === 'string') out.push(value);
+ else if (Array.isArray(value)) for (const v of value) allTargets(v, out);
+ else if (isRecord(value))
+ for (const v of Object.values(value)) allTargets(v, out);
+ return out;
+}
+
+/**
+ * @typedef {object} SubpathDeclaration
+ * @property {'declared'|'no_exports'|'root_only'|'missing'|'blocked'|'not_importable'} state
+ * @property {unknown} [value] the matched export value
+ * @property {string} [wildcard] what a `*` key matched
+ */
+
+/**
+ * How a package's `exports` field declares one subpath, without touching the
+ * targets: a missing key, a key with only a `require` condition, an `exports`
+ * that is a bare string or a condition object (so only `.`), a wildcard that
+ * does not match, or a `null` that blocks it. An `exports` of `null` is no
+ * `exports` field, as Node reads it.
+ * @param {unknown} exportsField
+ * @param {string} subpath `.` or `./…`
+ * @returns {SubpathDeclaration}
+ */
+export function subpathDeclaration(exportsField, subpath) {
+ if (exportsField == null) return {state: 'no_exports'};
+ const keys = isRecord(exportsField) ? Object.keys(exportsField) : [];
+ // An empty object is a subpath map with no keys: it exports nothing, so
+ // every subpath (the root too) is missing from it.
+ const isMap =
+ isRecord(exportsField) && keys.every(key => key.startsWith('.'));
+ if (!isMap) {
+ if (subpath !== '.') return {state: 'root_only'};
+ return importable(exportsField)
+ ? {state: 'declared', value: exportsField}
+ : {state: 'not_importable', value: exportsField};
+ }
+ const map = /** @type {Record<string, unknown>} */ (exportsField);
+ /** @type {{value: unknown, wildcard: string} | null} */
+ let hit = null;
+ if (Object.hasOwn(map, subpath)) {
+ hit = {value: map[subpath], wildcard: ''};
+ } else {
+ const patterns = keys
+ .filter(key => key.split('*').length === 2)
+ .sort((a, b) => b.indexOf('*') - a.indexOf('*') || b.length - a.length);
+ for (const pattern of patterns) {
+ const star = pattern.indexOf('*');
+ const prefix = pattern.slice(0, star);
+ const suffix = pattern.slice(star + 1);
+ if (
+ subpath.length >= prefix.length + suffix.length &&
+ subpath.startsWith(prefix) &&
+ subpath.endsWith(suffix)
+ ) {
+ hit = {
+ value: map[pattern],
+ wildcard: subpath.slice(
+ prefix.length,
+ subpath.length - suffix.length,
+ ),
+ };
+ break;
+ }
+ }
+ }
+ if (!hit) return {state: 'missing'};
+ if (hit.value == null) return {state: 'blocked'};
+ if (!importable(hit.value))
+ return {state: 'not_importable', value: hit.value, wildcard: hit.wildcard};
+ return {state: 'declared', value: hit.value, wildcard: hit.wildcard};
+}
diff --git a/packages/cli/foundation/integrations/public-imports.mjs b/packages/cli/foundation/integrations/public-imports.mjs
new file mode 100644
index 0000000000..bd9b6413e8
--- /dev/null
+++ b/packages/cli/foundation/integrations/public-imports.mjs
@@ -0,0 +1,976 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Source-level checks that what an integration package tells apps to
+ * import is importable, read without a build.
+ *
+ * @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.
+ * @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.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {parse} from '@babel/parser';
+import {findProjectCoreDir} from '../fs/paths.mjs';
+import {normalizeProviderId} from '../identity/provider-identity.mjs';
+import {
+ discoverIntegrationComponents,
+ resolveIntegrationImportPath,
+} from '../discovery/component-discovery.mjs';
+import {loadComponentDoc} from '../discovery/component-loader.mjs';
+import {discoverIntegrationTemplatesForOne} from '../discovery/template-adapter.mjs';
+import {
+ allTargets,
+ importable,
+ isRecord,
+ subpathDeclaration,
+} from './exports-subpaths.mjs';
+
+/**
+ * @typedef {import('./issue').AstryxIntegrationIssue} Issue
+ */
+
+const CORE = '@astryxdesign/core';
+const MODULE_EXTENSIONS = [
+ '.tsx',
+ '.ts',
+ '.mts',
+ '.jsx',
+ '.mjs',
+ '.js',
+ '.cjs',
+ '.cts',
+];
+
+/** @param {string} file */
+function readJson(file) {
+ try {
+ return JSON.parse(fs.readFileSync(file, 'utf-8'));
+ } catch {
+ return null;
+ }
+}
+
+/** @param {string} file */
+function isFile(file) {
+ try {
+ return fs.statSync(file).isFile();
+ } catch {
+ return false;
+ }
+}
+
+/** @param {string} from @param {string} to */
+function rel(from, to) {
+ return path.relative(from, to).split(path.sep).join('/');
+}
+
+// ── Import specifiers ───────────────────────────────────────────────
+
+/**
+ * Split a bare specifier into its package name and `./`-prefixed subpath.
+ * @param {string} specifier
+ * @returns {{pkg: string, subpath: string} | null}
+ */
+export function splitSpecifier(specifier) {
+ const m = /^((?:@[^/\s]+\/)?[^/\s]+)(\/.*)?$/.exec(specifier);
+ if (!m || specifier.startsWith('.') || specifier.startsWith('/')) return null;
+ return {pkg: m[1], subpath: m[2] ? `.${m[2]}` : '.'};
+}
+
+/**
+ * @typedef {object} ImportBinding
+ * @property {string} imported the exported name (`default` for a default import)
+ * @property {boolean} typeOnly
+ */
+
+/**
+ * @typedef {object} ImportStatement
+ * @property {string} source
+ * @property {ImportBinding[]} names
+ * @property {boolean} namespace
+ * @property {boolean} [typeOnly] the whole statement is `import type`
+ */
+
+const PARSE_PLUGINS = /** @type {any} */ ([
+ 'jsx',
+ 'typescript',
+ 'decorators-legacy',
+ 'importAttributes',
+ 'exportDefaultFrom',
+]);
+
+/** @param {string} text */
+function parseModuleText(text) {
+ return parse(text, {
+ sourceType: 'module',
+ allowImportExportEverywhere: true,
+ allowReturnOutsideFunction: true,
+ allowAwaitOutsideFunction: true,
+ errorRecovery: true,
+ plugins: PARSE_PLUGINS,
+ });
+}
+
+const IMPORT_RE =
+ /(?:^|[;\n])\s*import\s+(type\s+)?([^'";]*?)\s*from\s*['"]([^'"]+)['"]/g;
+
+/**
+ * Read the import statements of a module or a snippet: named, default,
+ * aliased, namespace and type-only. A snippet that does not parse (an example
+ * with elisions, say) falls back to reading `import … from '…'` lines.
+ * @param {string} text
+ * @returns {ImportStatement[]}
+ */
+export function readImports(text) {
+ /** @type {ImportStatement[]} */
+ const out = [];
+ let ast;
+ try {
+ ast = parseModuleText(text);
+ } catch {
+ // Not a module: read the import lines below.
+ }
+ if (ast) {
+ for (const node of ast.program.body) {
+ if (node.type !== 'ImportDeclaration') continue;
+ const typeOnly = node.importKind === 'type';
+ /** @type {ImportStatement} */
+ const statement = {
+ source: String(node.source.value),
+ names: [],
+ namespace: false,
+ typeOnly,
+ };
+ for (const s of node.specifiers ?? []) {
+ if (s.type === 'ImportDefaultSpecifier') {
+ statement.names.push({imported: 'default', typeOnly});
+ } else if (s.type === 'ImportNamespaceSpecifier') {
+ statement.namespace = true;
+ } else if (s.type === 'ImportSpecifier') {
+ const imported =
+ s.imported.type === 'Identifier'
+ ? s.imported.name
+ : String(s.imported.value);
+ statement.names.push({
+ imported,
+ typeOnly: typeOnly || s.importKind === 'type',
+ });
+ }
+ }
+ out.push(statement);
+ }
+ return out;
+ }
+ for (const m of text.matchAll(IMPORT_RE)) {
+ const typeOnly = Boolean(m[1]);
+ const clause = m[2].trim();
+ /** @type {ImportStatement} */
+ const statement = {
+ source: m[3],
+ names: [],
+ namespace: /\*\s*as\s/.test(clause),
+ typeOnly,
+ };
+ const braces = /\{([^}]*)\}/.exec(clause);
+ const head = clause
+ .replace(/\{[^}]*\}/, '')
+ .replace(/\*\s*as\s+[\w$]+/, '');
+ const defaultName = /^([\w$]+)/.exec(head.trim());
+ if (defaultName) statement.names.push({imported: 'default', typeOnly});
+ if (braces) {
+ for (const part of braces[1].split(',')) {
+ const item = part.trim();
+ if (!item) continue;
+ const t = /^type\s+/.test(item);
+ const name = item
+ .replace(/^type\s+/, '')
+ .split(/\s+as\s+/)[0]
+ .trim();
+ if (/^[\w$]+$/.test(name))
+ statement.names.push({imported: name, typeOnly: typeOnly || t});
+ }
+ }
+ out.push(statement);
+ }
+ return out;
+}
+
+// ── package.json exports ────────────────────────────────────────────
+
+/** @typedef {import('./exports-subpaths.mjs').SubpathDeclaration} SubpathDeclaration */
+
+/**
+ * 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
+ * module extension, or a folder index) counts as declared.
+ * @param {unknown} exportsField
+ * @param {string} packageDir
+ * @param {string} subpath
+ * @returns {SubpathDeclaration}
+ */
+function declarationIn(exportsField, packageDir, subpath) {
+ const declaration = subpathDeclaration(exportsField, subpath);
+ if (declaration.state !== 'no_exports') return declaration;
+ if (subpath === '.') return {state: 'declared', value: null, wildcard: ''};
+ const root = path.resolve(packageDir);
+ const base = path.resolve(root, subpath.slice(2));
+ if (!base.startsWith(root + path.sep)) return declaration;
+ const file = [
+ base,
+ ...MODULE_EXTENSIONS.map(ext => `${base}${ext}`),
+ ...MODULE_EXTENSIONS.map(ext => path.join(base, `index${ext}`)),
+ ].find(isFile);
+ return file
+ ? {state: 'declared', value: `./${rel(root, file)}`, wildcard: ''}
+ : declaration;
+}
+
+/**
+ * A declared subpath of the package whose target is `file`, if any: an exact
+ * key, or a wildcard key whose target pattern matches the file.
+ * @param {unknown} exportsField
+ * @param {string} packageDir
+ * @param {string} file
+ * @returns {string | null}
+ */
+function subpathFor(exportsField, packageDir, file) {
+ if (!isRecord(exportsField)) return null;
+ const wanted = `./${rel(packageDir, file)}`;
+ for (const [key, value] of Object.entries(exportsField)) {
+ if (!key.startsWith('.') || !importable(value)) continue;
+ for (const target of allTargets(value)) {
+ if (!key.includes('*')) {
+ if (target === wanted) return key;
+ continue;
+ }
+ const star = target.indexOf('*');
+ if (star === -1) continue;
+ const prefix = target.slice(0, star);
+ const suffix = target.slice(star + 1);
+ if (
+ wanted.startsWith(prefix) &&
+ wanted.endsWith(suffix) &&
+ wanted.length >= prefix.length + suffix.length
+ ) {
+ return key.replace(
+ '*',
+ wanted.slice(prefix.length, wanted.length - suffix.length),
+ );
+ }
+ }
+ }
+ return null;
+}
+
+/**
+ * The condition names an export value uses, at any depth, in order.
+ * @param {unknown} value
+ * @param {string[]} [out]
+ * @returns {string[]}
+ */
+function conditionNames(value, out = []) {
+ if (Array.isArray(value)) for (const v of value) conditionNames(v, out);
+ else if (isRecord(value)) {
+ for (const [key, v] of Object.entries(value)) {
+ if (!out.includes(key)) out.push(key);
+ conditionNames(v, out);
+ }
+ }
+ return out;
+}
+
+/**
+ * Why a declared state is not importable, in words.
+ * @param {SubpathDeclaration} declaration
+ * @param {string} subpath
+ */
+function whyUndeclared(declaration, subpath) {
+ const {state} = declaration;
+ switch (state) {
+ case 'no_exports':
+ return `package.json has no "exports" and no file exists at "${subpath}"`;
+ case 'root_only':
+ return `package.json "exports" names only the package root, which blocks every subpath`;
+ case 'blocked':
+ return `package.json "exports" maps "${subpath}" to null`;
+ case 'not_importable': {
+ const names = conditionNames(declaration.value);
+ const listed = names.map(name => `"${name}"`).join(', ');
+ return names.length === 0
+ ? `package.json "exports" gives "${subpath}" no target an ES module import can load`
+ : `package.json "exports" gives "${subpath}" only the ${listed} condition${names.length === 1 ? '' : 's'}, none of which an ES module import loads`;
+ }
+ default:
+ return `package.json "exports" does not declare "${subpath}"`;
+ }
+}
+
+/**
+ * The paste-ready package.json change that declares `subpath` → `target`.
+ * @param {unknown} exportsField
+ * @param {SubpathDeclaration['state']} state
+ * @param {string} subpath
+ * @param {string} target `./`-prefixed package-relative file
+ */
+function exportsFix(exportsField, state, subpath, target) {
+ const entry = `${JSON.stringify(subpath)}: ${JSON.stringify(target)}`;
+ if (state === 'no_exports') {
+ return `point it at a file the package ships, or add "exports": {${entry}} to package.json (an "exports" map makes every path it does not list private, so list "." and the package's other public paths too).`;
+ }
+ if (state === 'root_only') {
+ return `make "exports" a subpath map: {".": ${JSON.stringify(exportsField)}, ${entry}}.`;
+ }
+ if (state === 'not_importable') {
+ return `add an ES module condition to "${subpath}" in package.json "exports", e.g. "default": ${JSON.stringify(target)} (or the built file).`;
+ }
+ if (state === 'blocked') {
+ return `replace the null for "${subpath}" in package.json "exports" with ${JSON.stringify(target)}, or stop advertising it.`;
+ }
+ return `add ${entry} to package.json "exports" (or the built file it compiles to).`;
+}
+
+/**
+ * Whether `name` is a bare npm package name (an optional `@scope/` and a
+ * name), the only form an import can name the package by.
+ * @param {string} name
+ */
+function isPackageName(name) {
+ try {
+ normalizeProviderId(name);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+// ── Listed findings ─────────────────────────────────────────────────
+
+/**
+ * A public-import finding as a note on validate's result: listed with its
+ * fix inside the message, never counted or failed on. It becomes a failing
+ * warning in the next minor release (a new failure code joins only in a
+ * minor).
+ * @param {string} code
+ * @param {string} message
+ * @returns {PublicImportNote}
+ */
+function listed(code, message) {
+ return {code, message};
+}
+
+// ── Checks ──────────────────────────────────────────────────────────
+
+/**
+ * @typedef {object} Context
+ * @property {string} packageDir
+ * @property {string | null} name the package name; null when package.json has
+ * none, and then no import of the package's own name is judged
+ * @property {unknown} exportsField
+ * @property {string | null} coreDir
+ * @property {any} corePkg
+ * @property {PublicImportUnchecked[]} unchecked what could not be judged
+ * @property {string[]} files the package.json `files` entries, normalized
+ * @property {string[]} roots the integration's contribution roots, absolute
+ */
+
+const BUILT_EXTENSION_RE = /\.[cm]?jsx?$/u;
+
+/**
+ * Whether an undeclared deep path, in a package with no `exports`, points
+ * into build output that is not built yet: its top folder is missing, or is
+ * a `files` folder that holds no contribution root. Such an import cannot be
+ * judged from source.
+ * @param {Context} ctx
+ * @param {string} subpath
+ * @param {SubpathDeclaration} declaration
+ */
+function unbuiltOutput(ctx, subpath, declaration) {
+ if (declaration.state !== 'no_exports' || subpath === '.') return false;
+ const top = subpath.slice(2).split('/')[0];
+ if (!top) return false;
+ const topDir = path.resolve(ctx.packageDir, top);
+ if (!fs.existsSync(topDir)) return true;
+ return (
+ ctx.files.includes(top) &&
+ !ctx.roots.some(
+ root => root === topDir || root.startsWith(topDir + path.sep),
+ )
+ );
+}
+
+/**
+ * The reason an import into unbuilt output is listed as not checked.
+ * @param {string} subpath
+ */
+function unbuiltReason(subpath) {
+ return `package.json has no "exports", and "${subpath}" is build output that is not built yet, so it was not checked`;
+}
+
+/**
+ * The target a fix maps `subpath` to: the component's source for a source
+ * path, never a TypeScript source for a built `.js` path.
+ * @param {string} subpath
+ * @param {string | null} sourceTarget
+ */
+function fixTarget(subpath, sourceTarget) {
+ if (
+ sourceTarget &&
+ !(
+ BUILT_EXTENSION_RE.test(subpath) && !BUILT_EXTENSION_RE.test(sourceTarget)
+ )
+ ) {
+ return sourceTarget;
+ }
+ return BUILT_EXTENSION_RE.test(subpath)
+ ? `<the built file "${subpath}" names>`
+ : `./${subpath.slice(2)}.tsx`;
+}
+
+/** @typedef {import('../../api/integration/validate-integration.type.mjs').PublicImportUnchecked} PublicImportUnchecked */
+/** @typedef {import('../../api/integration/validate-integration.type.mjs').PublicImportsReport} PublicImportsReport */
+/** @typedef {{code: string, message: string}} PublicImportNote */
+
+/**
+ * Whether nothing a statement imports exists at run time: a statement-level
+ * `import type`, or named bindings that are each an inline `type`.
+ * @param {ImportStatement} statement
+ */
+function typeOnlyStatement(statement) {
+ if (statement.typeOnly) return true;
+ return (
+ !statement.namespace &&
+ statement.names.length > 0 &&
+ statement.names.every(binding => binding.typeOnly)
+ );
+}
+
+/**
+ * The files the `types` conditions of an export value name that an ES module
+ * import can reach (never one under `require`), with a wildcard filled in.
+ * @param {unknown} value
+ * @param {string} wildcard
+ * @param {boolean} [underTypes]
+ * @param {string[]} [out]
+ * @returns {string[]}
+ */
+function typesTargets(value, wildcard, underTypes = false, out = []) {
+ if (typeof value === 'string') {
+ if (underTypes) out.push(value.replace('*', wildcard));
+ } else if (Array.isArray(value)) {
+ for (const v of value) typesTargets(v, wildcard, underTypes, out);
+ } else if (isRecord(value)) {
+ for (const [condition, v] of Object.entries(value)) {
+ if (condition === 'require') continue;
+ typesTargets(v, wildcard, underTypes || condition === 'types', out);
+ }
+ }
+ return out;
+}
+
+/**
+ * The names a declaration file exports as types: exported interfaces and
+ * type aliases, `export type {…}`, and `export {…}` of a local interface or
+ * type alias. Anything else (a value, an `export *`) is not counted, so an
+ * import of it is listed as not checked. Null when the file cannot be read.
+ * @param {string} file
+ * @returns {Set<string> | null}
+ */
+function declaredTypeNames(file) {
+ let ast;
+ try {
+ ast = parse(fs.readFileSync(file, 'utf-8'), {
+ sourceType: 'module',
+ errorRecovery: true,
+ plugins: /** @type {any} */ ([
+ ['typescript', {dts: /\.d\.[cm]?ts$/u.test(file)}],
+ ]),
+ });
+ } catch {
+ return null;
+ }
+ /** @type {Set<string>} */
+ const local = new Set();
+ /** @type {Set<string>} */
+ const names = new Set();
+ /** @param {any} node */
+ const typeName = node =>
+ node &&
+ (node.type === 'TSInterfaceDeclaration' ||
+ node.type === 'TSTypeAliasDeclaration')
+ ? node.id.name
+ : null;
+ for (const node of ast.program.body) {
+ const own = typeName(node);
+ if (own) local.add(own);
+ if (node.type === 'ExportNamedDeclaration') {
+ const declared = typeName(node.declaration);
+ if (declared) local.add(declared);
+ }
+ }
+ /** @param {any} n */
+ const exportedName = n =>
+ n.type === 'Identifier' ? n.name : String(n.value);
+ for (const node of ast.program.body) {
+ if (node.type !== 'ExportNamedDeclaration') continue;
+ const declared = typeName(node.declaration);
+ if (declared) names.add(declared);
+ for (const s of node.specifiers ?? []) {
+ if (s.type !== 'ExportSpecifier') continue;
+ const exported = exportedName(s.exported);
+ if (node.exportKind === 'type' || s.exportKind === 'type')
+ names.add(exported);
+ else if (!node.source && local.has(exportedName(s.local)))
+ names.add(exported);
+ }
+ }
+ return names;
+}
+
+/**
+ * An import of a subpath whose `exports` entry has only `types` targets is
+ * never judged as a run-time import: accepted when it is `import type`, its
+ * every binding is an inline `type`, or every name it imports is one the
+ * `types` file declares as a type; otherwise the reason it was not checked.
+ * @param {Context} ctx
+ * @param {ImportStatement} statement
+ * @param {string} subpath
+ * @param {SubpathDeclaration} declaration
+ * @returns {string | null}
+ */
+function typesOnlyImport(ctx, statement, subpath, declaration) {
+ if (typeOnlyStatement(statement)) return null;
+ const not = `"${subpath}" reaches an ES module import only through a "types" target in package.json "exports", which nothing loads at run time`;
+ if (statement.namespace || statement.names.length === 0)
+ return `${not}, and a namespace or side-effect import of it cannot be judged from source, so it was not checked`;
+ const files = typesTargets(declaration.value, declaration.wildcard ?? '');
+ /** @type {Set<string>} */
+ const types = new Set();
+ let read = false;
+ for (const target of files) {
+ const found = declaredTypeNames(path.resolve(ctx.packageDir, target));
+ if (!found) continue;
+ read = true;
+ for (const n of found) types.add(n);
+ }
+ if (!read)
+ return `${not}, and its types file ${files.map(f => `"${f}"`).join(', ')} could not be read (it may be build output), so it was not checked`;
+ const unknown = statement.names
+ .filter(binding => !binding.typeOnly && !types.has(binding.imported))
+ .map(binding => binding.imported);
+ if (unknown.length === 0) return null;
+ return `${not}, and its types file does not declare ${unknown.join(', ')} as a type, so it was not checked`;
+}
+
+/**
+ * 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.
+ * @param {Context} ctx
+ * @param {ImportStatement} statement
+ * @param {string} subpath
+ * @returns {{undeclared: SubpathDeclaration | null, unchecked?: string}}
+ */
+function undeclaredOwnImport(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
+ // a type import, never as a run-time one.
+ if (
+ 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};
+ }
+ return {undeclared: declaration.state === 'declared' ? null : declaration};
+}
+
+/**
+ * A component doc's import specifier, and every example's imports.
+ * @param {Context} ctx
+ * @param {any} integration
+ * @returns {Promise<PublicImportNote[]>}
+ */
+async function componentIssues(ctx, integration) {
+ /** @type {PublicImportNote[]} */
+ const issues = [];
+ // Every component check compares imports with the package's own name.
+ if (ctx.name == null) return issues;
+ let records;
+ try {
+ records = discoverIntegrationComponents(integration);
+ } catch {
+ return issues; // an unreadable root is reported by the root validators
+ }
+ /** @type {Map<string, typeof records>} */
+ const byDoc = new Map();
+ for (const record of records) {
+ const list = byDoc.get(record.docPath) ?? [];
+ list.push(record);
+ byDoc.set(record.docPath, list);
+ }
+ for (const [docPath, list] of byDoc) {
+ let doc;
+ try {
+ doc = await loadComponentDoc(docPath);
+ } catch {
+ continue; // reported by the doc validators
+ }
+ if (!isRecord(doc)) continue;
+ const shownDoc = rel(ctx.packageDir, docPath);
+ const record = list[0];
+ const source = record.sourcePath;
+ const sourceTarget = source ? `./${rel(ctx.packageDir, source)}` : null;
+ // The import the doc writes, or the one the CLI derives for it (its
+ // folder's subpath when exported, else the package root).
+ const authored = typeof doc.import === 'string' ? doc.import : null;
+ const specifier =
+ authored ??
+ resolveIntegrationImportPath(
+ {
+ exportsMap: /** @type {any} */ (ctx.exportsField) ?? null,
+ packageDir: ctx.packageDir,
+ docPath,
+ packageName: ctx.name,
+ },
+ record.name,
+ );
+ const split = splitSpecifier(specifier);
+ // The entry that exports this component alone, and the doc import that
+ // uses it: never one component's file as the package root or folder.
+ const entryKey = sourceTarget
+ ? sourceTarget.replace(/\.[cm]?[jt]sx?$/u, '')
+ : null;
+ const perComponent = entryKey
+ ? `add "${entryKey}": "${sourceTarget}" to package.json "exports" and set import: '${ctx.name}${entryKey.slice(1)}' in the doc`
+ : null;
+ const gives = authored
+ ? `gives import "${specifier}"`
+ : `has no import, so apps are told to import from "${specifier}"`;
+ const declared = source
+ ? subpathFor(ctx.exportsField, ctx.packageDir, source)
+ : null;
+ const suggested =
+ declared ??
+ (sourceTarget ? sourceTarget.replace(/\.[cm]?[jt]sx?$/u, '') : null);
+ if (split && split.pkg !== ctx.name) {
+ issues.push(
+ listed(
+ 'component_import_other_package',
+ `Component doc "${shownDoc}" ${gives}, which names package "${split.pkg}", not this package "${ctx.name}", so apps are told to import the component from somewhere it is not. Fix: set import: '${ctx.name}${suggested ? suggested.slice(1) : ''}' in the doc.`,
+ ),
+ );
+ } else if (split) {
+ const declaration = declarationIn(
+ ctx.exportsField,
+ ctx.packageDir,
+ split.subpath,
+ );
+ if (unbuiltOutput(ctx, split.subpath, declaration)) {
+ ctx.unchecked.push({
+ file: shownDoc,
+ specifier,
+ reason: unbuiltReason(split.subpath),
+ });
+ } else if (declaration.state !== 'declared') {
+ const already =
+ declared && declared !== split.subpath
+ ? `set import: '${ctx.name}${declared.slice(1)}' (already exported), or `
+ : '';
+ issues.push(
+ listed(
+ 'component_import_not_exported',
+ `Component doc "${shownDoc}" ${gives}, but ${whyUndeclared(declaration, split.subpath)}, so apps cannot import the component from it. Fix: ${already}${split.subpath === '.' && perComponent ? `${perComponent}.` : exportsFix(ctx.exportsField, declaration.state, split.subpath, fixTarget(split.subpath, sourceTarget))}`,
+ ),
+ );
+ }
+ }
+
+ /**
+ * 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.
+ * @param {ImportStatement} statement
+ * @param {string} subpath
+ * @param {SubpathDeclaration} undeclared
+ */
+ const exampleFix = (statement, subpath, undeclared) => {
+ const values = statement.names
+ .filter(binding => !binding.typeOnly)
+ .map(binding => binding.imported);
+ const atSubpath = [
+ '',
+ ...MODULE_EXTENSIONS,
+ ...MODULE_EXTENSIONS.map(ext => `/index${ext}`),
+ ]
+ .map(ext => path.resolve(ctx.packageDir, `${subpath.slice(2)}${ext}`))
+ .find(
+ file =>
+ 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 target = atSubpath
+ ? `./${rel(ctx.packageDir, atSubpath)}`
+ : onlyDocumented && sourceTarget
+ ? fixTarget(subpath, sourceTarget)
+ : `<the file that exports ${values.join(', ') || 'them'}>`;
+ return exportsFix(ctx.exportsField, undeclared.state, subpath, target);
+ };
+
+ const examples = Array.isArray(doc.examples) ? doc.examples : [];
+ for (const [index, example] of examples.entries()) {
+ if (!isRecord(example) || typeof example.code !== 'string') continue;
+ const label =
+ typeof example.label === 'string'
+ ? `"${example.label}"`
+ : `#${index + 1}`;
+ for (const statement of readImports(example.code)) {
+ const parts = splitSpecifier(statement.source);
+ if (!parts || parts.pkg !== ctx.name) continue;
+ const {undeclared, unchecked} = undeclaredOwnImport(
+ ctx,
+ statement,
+ parts.subpath,
+ );
+ if (unchecked) {
+ ctx.unchecked.push({
+ file: shownDoc,
+ specifier: statement.source,
+ reason: `example ${label}: ${unchecked}`,
+ });
+ } else if (
+ undeclared &&
+ unbuiltOutput(ctx, parts.subpath, undeclared)
+ ) {
+ ctx.unchecked.push({
+ file: shownDoc,
+ specifier: statement.source,
+ reason: `example ${label}: ${unbuiltReason(parts.subpath)}`,
+ });
+ } else if (undeclared) {
+ issues.push(
+ listed(
+ 'example_import_not_exported',
+ `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)}`,
+ ),
+ );
+ }
+ }
+ }
+ }
+ return issues;
+}
+
+/**
+ * Template public imports and what each template source imports.
+ * @param {Context} ctx
+ * @param {any} integration
+ * @returns {Promise<PublicImportNote[]>}
+ */
+async function templateIssues(ctx, integration) {
+ /** @type {PublicImportNote[]} */
+ const issues = [];
+ const root = integration.templates;
+ if (!root) return issues;
+ let templates;
+ try {
+ ({templates} = await discoverIntegrationTemplatesForOne(integration));
+ } catch {
+ return issues;
+ }
+ for (const template of templates) {
+ const id = template.dirName;
+ const file = template.filePath;
+ const shown = rel(ctx.packageDir, file);
+ const sourceTarget = `./${shown}`;
+ const subpath = `./${shown.replace(/\.tsx?$/u, '')}`;
+ const declaration = declarationIn(
+ ctx.exportsField,
+ ctx.packageDir,
+ subpath,
+ );
+ if (ctx.name != null && declaration.state !== 'declared') {
+ issues.push(
+ listed(
+ 'template_import_not_exported',
+ `Template "${id}" has public import "${ctx.name}${subpath.slice(1)}", but ${whyUndeclared(declaration, subpath)}, so it cannot be imported once published. Fix: ${exportsFix(ctx.exportsField, declaration.state, subpath, sourceTarget)}`,
+ ),
+ );
+ }
+
+ let text;
+ try {
+ text = fs.readFileSync(file, 'utf-8');
+ } catch {
+ text = '';
+ }
+ for (const statement of readImports(text)) {
+ const spec = statement.source;
+ if (spec.startsWith('.')) {
+ const target = path.resolve(path.dirname(file), spec);
+ if (target !== root && !target.startsWith(root + path.sep)) {
+ issues.push(
+ listed(
+ 'template_import_outside_root',
+ `Template "${id}" (${shown}) imports "${spec}", a path outside the templates root; \`astryx template\` copies only the template into an app, where that path does not exist. Fix: import it through the package's public name (e.g. '${ctx.name ?? '<package name>'}/…' declared in package.json "exports"), or move the code into the template.`,
+ ),
+ );
+ }
+ continue;
+ }
+ const parts = splitSpecifier(spec);
+ if (!parts) continue;
+ if (ctx.name != null && parts.pkg === ctx.name) {
+ const {undeclared, unchecked} = undeclaredOwnImport(
+ ctx,
+ statement,
+ parts.subpath,
+ );
+ if (unchecked) {
+ ctx.unchecked.push({file: shown, specifier: spec, reason: unchecked});
+ } else if (
+ undeclared &&
+ unbuiltOutput(ctx, parts.subpath, undeclared)
+ ) {
+ ctx.unchecked.push({
+ file: shown,
+ specifier: spec,
+ reason: unbuiltReason(parts.subpath),
+ });
+ } else if (undeclared) {
+ issues.push(
+ listed(
+ 'template_private_import',
+ `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 (parts.pkg === CORE && !ctx.corePkg) {
+ ctx.unchecked.push({
+ file: shown,
+ specifier: spec,
+ reason:
+ '@astryxdesign/core is not installed, so Core\'s package.json "exports" could not be read',
+ });
+ } else if (parts.pkg === CORE && ctx.corePkg && parts.subpath !== '.') {
+ const core = declarationIn(
+ ctx.corePkg.exports,
+ /** @type {string} */ (ctx.coreDir),
+ parts.subpath,
+ );
+ if (core.state !== 'declared') {
+ const top = parts.subpath
+ .split('/')
+ .filter(s => s && s !== '.' && s !== 'src')[0];
+ const hint =
+ top &&
+ subpathDeclaration(ctx.corePkg.exports, `./${top}`).state ===
+ 'declared'
+ ? `'${CORE}/${top}'`
+ : `a subpath Core's package.json "exports" declares`;
+ issues.push(
+ listed(
+ 'template_private_import',
+ `Template "${id}" (${shown}) imports "${spec}", a path Core's package.json "exports" does not declare, so the template breaks in an app. Fix: import from ${hint}.`,
+ ),
+ );
+ }
+ }
+ }
+ }
+ return issues;
+}
+
+/**
+ * Every public-import finding for one package, as notes, and the report of
+ * what could not be judged. It returns no issues: the notes are listed
+ * only, and fail `--strict` from the next minor release.
+ * @param {string} packageDir
+ * @param {any} integration the loaded integration record
+ * @returns {Promise<{issues: Issue[], notes: PublicImportNote[], report: PublicImportsReport}>}
+ * `issues` is always empty: kept so validate's call site stays one shape
+ */
+export async function publicImportIssues(packageDir, integration) {
+ /** @type {PublicImportsReport} */
+ const report = {status: 'checked', findings: [], unchecked: []};
+ const pkg = readJson(path.join(packageDir, 'package.json'));
+ // What cannot run is listed as not checked, never a skip `--strict` would
+ // fail on.
+ if (!isRecord(pkg)) {
+ report.unchecked.push({
+ file: 'package.json',
+ specifier: '',
+ reason: 'package.json could not be read, so no import was checked',
+ });
+ return {issues: [], notes: [], report};
+ }
+ const raw = typeof pkg.name === 'string' && pkg.name !== '' ? pkg.name : null;
+ // A name that is not a bare package name (`acme/kit`) cannot be told apart
+ // from an import of another package: checked as if there were none.
+ const name = raw != null && isPackageName(raw) ? raw : null;
+ if (name == null) {
+ report.unchecked.push({
+ file: 'package.json',
+ specifier: '',
+ reason: `${raw == null ? 'package.json has no "name"' : `package.json "name" ${JSON.stringify(raw)} is not a bare package name`}, so imports of the package's own name were not checked; only template imports outside the templates root and of Core were`,
+ });
+ }
+ // The Core installed beside the package, which its templates' imports
+ // resolve against; never the CLI's own copy, which may be another release.
+ // A workspace's own `packages/core` (another package) is not it: then Core
+ // counts as not installed and its imports are listed as not checked.
+ const foundCore = name === CORE ? packageDir : findProjectCoreDir(packageDir);
+ const foundCorePkg = foundCore
+ ? readJson(path.join(foundCore, 'package.json'))
+ : null;
+ const isCore = isRecord(foundCorePkg) && foundCorePkg.name === CORE;
+ /** @type {Context} */
+ const ctx = {
+ packageDir,
+ name,
+ exportsField: pkg.exports,
+ coreDir: isCore ? foundCore : null,
+ corePkg: isCore ? foundCorePkg : null,
+ unchecked: report.unchecked,
+ files: Array.isArray(pkg.files)
+ ? pkg.files
+ .filter(entry => typeof entry === 'string')
+ .map(entry => entry.replace(/^\.\//u, '').replace(/\/+$/u, ''))
+ : [],
+ roots: [
+ integration.components,
+ integration.templates,
+ integration.docs,
+ integration.themes,
+ integration.codemods,
+ ]
+ .filter(root => typeof root === 'string')
+ .map(root => path.resolve(root)),
+ };
+ const notes = [
+ ...(await componentIssues(ctx, integration)),
+ ...(await templateIssues(ctx, integration)),
+ ];
+ // Listed only: none is an issue, so none counts or fails a check.
+ return {issues: [], notes, report};
+}
diff --git a/packages/cli/foundation/integrations/public-imports.test.mjs b/packages/cli/foundation/integrations/public-imports.test.mjs
new file mode 100644
index 0000000000..6a826d8bea
--- /dev/null
+++ b/packages/cli/foundation/integrations/public-imports.test.mjs
@@ -0,0 +1,868 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Source-level public-import checks run by
+ * `astryx doctor integration validate` (and so `integration check --strict`).
+ *
+ * Each test stands up a small integration package under the repo root (so the
+ * repo's own Core is the installed Core) and validates it.
+ */
+
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {spawnSync} from 'node:child_process';
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import {
+ validateIntegration,
+ validateLocalIntegration,
+} from '../../api/integration/validate-integration.mjs';
+import {readImports} from './public-imports.mjs';
+import {subpathDeclaration} from './exports-subpaths.mjs';
+import {
+ integrationAddComponent,
+ integrationAddTemplate,
+} from '../../api/integration/add-contribution.mjs';
+import {
+ integrationCheck,
+ strictIssues,
+} from '../../api/integration/check/check.mjs';
+import {CLI_ROOT} from '../fs/paths.mjs';
+
+const CODES = new Set([
+ 'component_import_not_exported',
+ 'component_import_other_package',
+ 'example_import_not_exported',
+ 'template_import_not_exported',
+ 'template_import_outside_root',
+ 'template_private_import',
+]);
+
+let dir;
+
+/** @param {string} file @param {string} text */
+function write(file, text) {
+ fs.mkdirSync(path.dirname(path.join(dir, file)), {recursive: true});
+ fs.writeFileSync(path.join(dir, file), text);
+}
+
+/** @param {(pkg: any) => void} edit */
+function pkg(edit) {
+ const file = path.join(dir, 'package.json');
+ const value = JSON.parse(fs.readFileSync(file, 'utf-8'));
+ edit(value);
+ fs.writeFileSync(file, JSON.stringify(value, null, 2));
+}
+
+const DOC = (
+ importPath = '@acme/widgets/components/AcmeWidget',
+ example = 'import {AcmeWidget} from \'@acme/widgets/components/AcmeWidget\';\\n\\n<AcmeWidget label=\\"Save\\" />',
+) =>
+ `export default {
+ type: 'component',
+ name: 'AcmeWidget',
+ displayName: 'Acme Widget',
+ import: '${importPath}',
+ usage: {description: 'A pressable widget.'},
+ props: [{name: 'label', type: 'string', description: 'Text.', required: true}],
+ examples: [{label: 'Basic', code: "${example}"}],
+};
+`;
+
+const BLOCK = () =>
+ `export default {
+ type: 'block',
+ name: 'account-card',
+ displayName: 'Account Card',
+ description: 'Account Card template.',
+ aspectRatio: 1,
+};
+`;
+
+beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-public-imports-'));
+ write(
+ 'package.json',
+ JSON.stringify({
+ name: '@acme/widgets',
+ version: '1.0.0',
+ type: 'module',
+ peerDependencies: {
+ '@astryxdesign/core': '>=0.1.0',
+ '@astryxdesign/cli': '>=0.1.0',
+ },
+ exports: {
+ './components/AcmeWidget': './components/AcmeWidget.tsx',
+ './templates/account-card': './templates/account-card.tsx',
+ },
+ }),
+ );
+ write(
+ 'astryx.integration.mjs',
+ "export default {components: './components', templates: './templates'};\n",
+ );
+ write('components/AcmeWidget.doc.mjs', DOC());
+ write(
+ 'components/AcmeWidget.tsx',
+ 'export type AcmeWidgetProps = {label: string};\nexport function AcmeWidget({label}: AcmeWidgetProps) {\n return <button>{label}</button>;\n}\n',
+ );
+ write('templates/account-card.doc.mjs', BLOCK());
+ write(
+ 'templates/account-card.tsx',
+ 'import {AcmeWidget} from \'@acme/widgets/components/AcmeWidget\';\nexport default function AccountCard() {\n return <AcmeWidget label="Account" />;\n}\n',
+ );
+});
+
+afterEach(() => {
+ fs.rmSync(dir, {recursive: true, force: true});
+});
+
+/** The public-import findings, listed as notes on validate's result. */
+async function found() {
+ const result = await validateLocalIntegration(dir);
+ return (result.notes ?? []).filter(note => CODES.has(note.code));
+}
+
+async function codes() {
+ return (await found()).map(issue => issue.code).sort();
+}
+
+describe('public imports: clean packages', () => {
+ it('passes the known-good package', async () => {
+ const result = await validateLocalIntegration(dir);
+ expect(result.issues).toEqual([]);
+ });
+
+ it('passes a condition object with import (types first) or default', async () => {
+ pkg(p => {
+ p.exports['./components/AcmeWidget'] = {
+ types: './components/AcmeWidget.tsx',
+ import: './components/AcmeWidget.tsx',
+ };
+ });
+ expect(await codes()).toEqual([]);
+ pkg(p => {
+ p.exports['./components/AcmeWidget'] = {
+ default: './components/AcmeWidget.tsx',
+ import: './missing.js',
+ };
+ });
+ expect(await codes()).toEqual([]);
+ });
+
+ it('passes a wildcard that covers the component', async () => {
+ pkg(p => {
+ delete p.exports['./components/AcmeWidget'];
+ p.exports['./components/*'] = './components/*.tsx';
+ });
+ expect(await codes()).toEqual([]);
+ });
+
+ it('checks a package whose name is not a bare package name as nameless', async () => {
+ pkg(p => {
+ p.name = 'acme/kit';
+ });
+ const result = await validateIntegration(undefined, {cwd: dir});
+ expect(await codes()).toEqual([]);
+ expect(result.data.publicImports?.unchecked).toContainEqual(
+ expect.objectContaining({
+ file: 'package.json',
+ reason: expect.stringContaining(
+ '"acme/kit" is not a bare package name',
+ ),
+ }),
+ );
+ });
+
+ it('reads "exports": null as no exports field', async () => {
+ pkg(p => {
+ p.exports = null;
+ });
+ // A doc module loads once per run, so the doc is written before checking.
+ write(
+ 'components/AcmeWidget.doc.mjs',
+ DOC('@acme/widgets/components/Missing'),
+ );
+ const issue = (await found()).find(
+ i => i.code === 'component_import_not_exported',
+ );
+ expect(issue?.message).toContain(
+ 'no file exists at "./components/Missing"',
+ );
+ // The template's deep path to its own file still resolves.
+ expect((await found()).filter(i => i.code.startsWith('template_'))).toEqual(
+ [],
+ );
+ });
+
+ it('keeps legacy deep paths when package.json has no exports', async () => {
+ pkg(p => delete p.exports);
+ expect(await codes()).toEqual([]);
+ });
+
+ it('flags a deep path with no file when package.json has no exports', async () => {
+ pkg(p => delete p.exports);
+ write(
+ 'components/AcmeWidget.doc.mjs',
+ DOC('@acme/widgets/components/Missing'),
+ );
+ const issue = (await found()).find(
+ i => i.code === 'component_import_not_exported',
+ );
+ expect(issue?.message).toContain(
+ 'no file exists at "./components/Missing"',
+ );
+ });
+
+ it('lists a deep path into build output not built yet as not checked', async () => {
+ pkg(p => {
+ delete p.exports;
+ p.files = ['dist', 'components', 'templates'];
+ });
+ write(
+ 'components/AcmeWidget.doc.mjs',
+ DOC(
+ '@acme/widgets/dist/AcmeWidget.js',
+ "import {AcmeWidget} from '@acme/widgets/dist/AcmeWidget.js';\\n<AcmeWidget />",
+ ),
+ );
+ const result = await validateIntegration(undefined, {cwd: dir});
+ expect(
+ (result.data.notes ?? []).filter(i => i.code.includes('_not_exported')),
+ ).toEqual([]);
+ expect(result.data.publicImports?.unchecked).toEqual([
+ expect.objectContaining({
+ file: 'components/AcmeWidget.doc.mjs',
+ specifier: '@acme/widgets/dist/AcmeWidget.js',
+ reason: expect.stringContaining('build output'),
+ }),
+ expect.objectContaining({
+ specifier: '@acme/widgets/dist/AcmeWidget.js',
+ }),
+ ]);
+ });
+
+ it('never maps a built .js path to the .tsx source in a fix', async () => {
+ pkg(p => delete p.exports);
+ write(
+ 'components/AcmeWidget.doc.mjs',
+ DOC('@acme/widgets/components/AcmeWidget.js'),
+ );
+ const issue = (await found()).find(
+ i => i.code === 'component_import_not_exported',
+ );
+ expect(issue?.message).not.toContain(
+ '"./components/AcmeWidget.js": "./components/AcmeWidget.tsx"',
+ );
+ });
+
+ it('never requires an exports target to exist (build output)', async () => {
+ pkg(p => {
+ p.exports['./components/AcmeWidget'] = {
+ types: './dist/AcmeWidget.d.ts',
+ import: './dist/AcmeWidget.js',
+ };
+ });
+ expect(await codes()).toEqual([]);
+ });
+});
+
+describe('public imports: component doc import', () => {
+ it('flags a missing exports key with the entry to add', async () => {
+ pkg(p => delete p.exports['./components/AcmeWidget']);
+ const issues = await found();
+ const issue = issues.find(i => i.code === 'component_import_not_exported');
+ expect(issue).not.toHaveProperty('severity');
+ expect(issue?.message).toContain(
+ '"./components/AcmeWidget": "./components/AcmeWidget.tsx"',
+ );
+ });
+
+ it('lists its findings only: neither validate nor --strict counts or fails on them', async () => {
+ pkg(p => {
+ delete p.exports['./components/AcmeWidget'];
+ });
+ write(
+ 'templates/account-card.tsx',
+ "import {X} from '../components/AcmeWidget';\nexport function A() {\n return <X />;\n}\n",
+ );
+ const issues = await found();
+ expect(issues.length).toBeGreaterThan(2);
+ expect(issues.every(i => !('severity' in i))).toBe(true);
+ const validated = await validateLocalIntegration(dir);
+ expect(validated.issues.filter(issue => CODES.has(issue.code))).toEqual([]);
+ const plain = await integrationCheck({cwd: dir});
+ expect(plain.data.errors).toBe(0);
+ expect(plain.data.warnings).toBe(0);
+ const strict = await integrationCheck({cwd: dir, strict: true});
+ expect(strict.data.failed).toBe(false);
+ expect(strict.data.failures).toEqual([]);
+ });
+
+ it('flags a require-only condition', async () => {
+ pkg(p => {
+ p.exports['./components/AcmeWidget'] = {
+ require: './components/AcmeWidget.tsx',
+ };
+ });
+ const issue = (await found()).find(
+ i => i.code === 'component_import_not_exported',
+ );
+ expect(issue?.message).toContain('only the "require" condition');
+ });
+
+ it('names the conditions a types-only entry has', async () => {
+ pkg(p => {
+ p.exports['./components/AcmeWidget'] = {types: './a.d.ts'};
+ });
+ const issue = (await found()).find(
+ i => i.code === 'component_import_not_exported',
+ );
+ expect(issue?.message).toContain('only the "types" condition');
+ expect(issue?.message).not.toContain('require');
+ });
+
+ it('flags a bare-string exports field', async () => {
+ pkg(p => {
+ p.exports = './components/AcmeWidget.tsx';
+ });
+ const all = await codes();
+ expect(all).toContain('component_import_not_exported');
+ expect(all).toContain('template_import_not_exported');
+ });
+
+ it('flags a wildcard that does not match', async () => {
+ pkg(p => {
+ delete p.exports['./components/AcmeWidget'];
+ p.exports['./widgets/*'] = './components/*.tsx';
+ });
+ expect(await codes()).toContain('component_import_not_exported');
+ });
+
+ it('points an undeclared import at the subpath already exported', async () => {
+ write('components/AcmeWidget.doc.mjs', DOC('@acme/widgets/AcmeWidget'));
+ const issue = (await found()).find(
+ i => i.code === 'component_import_not_exported',
+ );
+ expect(issue?.message).toContain(
+ "set import: '@acme/widgets/components/AcmeWidget' (already exported)",
+ );
+ });
+
+ it('flags an import that names another package', async () => {
+ write(
+ 'components/AcmeWidget.doc.mjs',
+ DOC('@acme/other/components/AcmeWidget'),
+ );
+ const issue = (await found()).find(
+ i => i.code === 'component_import_other_package',
+ );
+ expect(issue?.message).toContain(
+ "set import: '@acme/widgets/components/AcmeWidget'",
+ );
+ });
+});
+
+describe('public imports: component examples', () => {
+ it('flags a subpath exports does not declare', async () => {
+ write(
+ 'components/AcmeWidget.doc.mjs',
+ DOC(
+ undefined,
+ "import {AcmeWidget} from '@acme/widgets/src/AcmeWidget';\\n<AcmeWidget />",
+ ),
+ );
+ expect(await codes()).toEqual(['example_import_not_exported']);
+ });
+
+ 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(
+ i => i.code === 'example_import_not_exported',
+ );
+ expect(issue?.message).not.toContain('in the example, as the doc');
+ expect(issue?.message).toContain(
+ 'add "./components/AcmeWidget": "./components/AcmeWidget.tsx" to package.json "exports"',
+ );
+ });
+
+ it('gives the exports entry for a hooks path when the doc import lacks the hook', async () => {
+ write(
+ 'components/useAcmeTheme.ts',
+ 'export function useAcmeTheme() {\n return null;\n}\n',
+ );
+ write(
+ 'components/AcmeWidget.doc.mjs',
+ DOC(
+ undefined,
+ "import {useAcmeTheme} from '@acme/widgets/components/useAcmeTheme';\\nuseAcmeTheme();",
+ ),
+ );
+ const issue = (await found()).find(
+ i => i.code === 'example_import_not_exported',
+ );
+ expect(issue?.message).not.toContain(
+ "import from '@acme/widgets/components/AcmeWidget'",
+ );
+ expect(issue?.message).toContain(
+ 'add "./components/useAcmeTheme": "./components/useAcmeTheme.ts" to package.json "exports"',
+ );
+ });
+
+ it('accepts aliased, type-only and other-package imports', async () => {
+ write(
+ 'components/AcmeWidget.doc.mjs',
+ DOC(
+ undefined,
+ "import {AcmeWidget as W, type AcmeWidgetProps} from '@acme/widgets/components/AcmeWidget';\\nimport {Button} from '@astryxdesign/core/Button';\\nimport x from 'left-pad';\\n<W label=\\\"a\\\" />",
+ ),
+ );
+ expect(await codes()).toEqual([]);
+ });
+
+ it('reads named, default, aliased, namespace and type-only imports', () => {
+ const statements = readImports(
+ "import D, {A as B, type T} from 'p/a';\nimport type {U} from 'p/b';\nimport * as N from 'p/c';\n...\n<D />",
+ );
+ expect(statements.map(s => s.source)).toEqual(['p/a', 'p/b', 'p/c']);
+ expect(statements[0].names).toEqual([
+ {imported: 'default', typeOnly: false},
+ {imported: 'A', typeOnly: false},
+ {imported: 'T', typeOnly: true},
+ ]);
+ expect(statements[1].names).toEqual([{imported: 'U', typeOnly: true}]);
+ expect(statements[2].namespace).toBe(true);
+ });
+});
+
+describe('public imports: template sources', () => {
+ it('flags a relative import that leaves the templates root', async () => {
+ write(
+ 'templates/account-card.tsx',
+ 'import {AcmeWidget} from \'../components/AcmeWidget\';\nexport default function A() {\n return <AcmeWidget label="x" />;\n}\n',
+ );
+ expect(await codes()).toEqual(['template_import_outside_root']);
+ });
+
+ it('flags a Core path Core does not export, and accepts a public one', async () => {
+ write(
+ 'templates/account-card.tsx',
+ 'import {Button} from \'@astryxdesign/core/src/Button/Button\';\nexport default function A() {\n return <Button label="x" />;\n}\n',
+ );
+ const issue = (await found()).find(
+ i => i.code === 'template_private_import',
+ );
+ expect(issue?.message).toContain("'@astryxdesign/core/Button'");
+ write(
+ 'templates/account-card.tsx',
+ 'import {Button} from \'@astryxdesign/core/Button\';\nexport default function A() {\n return <Button 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(
+ i => i.code === 'template_import_not_exported',
+ );
+ expect(issue?.message).toContain(
+ '"./templates/account-card": "./templates/account-card.tsx"',
+ );
+ });
+});
+
+describe('subpathDeclaration', () => {
+ it('reads each way exports can declare a subpath', () => {
+ expect(subpathDeclaration(undefined, './a').state).toBe('no_exports');
+ expect(subpathDeclaration('./i.js', './a').state).toBe('root_only');
+ expect(subpathDeclaration({import: './i.js'}, './a').state).toBe(
+ 'root_only',
+ );
+ expect(subpathDeclaration({'./a': null}, './a').state).toBe('blocked');
+ expect(subpathDeclaration({'./a': {require: './a.cjs'}}, './a').state).toBe(
+ 'not_importable',
+ );
+ expect(subpathDeclaration({'./*': './src/*.ts'}, './a').state).toBe(
+ 'declared',
+ );
+ expect(
+ subpathDeclaration(
+ {'./*': './src/*.ts', './private/*': null},
+ './private/a',
+ ).state,
+ ).toBe('blocked');
+ });
+});
+
+describe('derived component imports', () => {
+ const NO_IMPORT = `export default {
+ type: 'component',
+ name: 'AcmeWidget',
+ displayName: 'Acme Widget',
+ usage: {description: 'A pressable widget.'},
+ props: [{name: 'label', type: 'string', description: 'Text.', required: true}],
+};
+`;
+
+ it('warns when the derived root import is not declared', async () => {
+ write('components/AcmeWidget.doc.mjs', NO_IMPORT);
+ const issue = (await found()).find(
+ i => i.code === 'component_import_not_exported',
+ );
+ expect(issue?.message).toContain(
+ 'has no import, so apps are told to import from "@acme/widgets"',
+ );
+ });
+});
+
+describe('fixes for two components in one folder', () => {
+ const docFor = (/** @type {string} */ name) => `export default {
+ type: 'component',
+ name: '${name}',
+ displayName: '${name}',
+ usage: {description: 'A widget.'},
+ props: [],
+};
+`;
+
+ beforeEach(() => {
+ for (const name of ['AcmeAlpha', 'AcmeBeta']) {
+ write(`components/${name}.doc.mjs`, docFor(name));
+ write(
+ `components/${name}.tsx`,
+ `export function ${name}() {\n return null;\n}\n`,
+ );
+ }
+ });
+
+ it('gives each import-less component its own entry, never the root', async () => {
+ const fixes = (await found())
+ .filter(i => i.code === 'component_import_not_exported')
+ .map(i => i.message.split('Fix: ')[1]);
+ expect(fixes).toEqual(
+ expect.arrayContaining([
+ `add "./components/AcmeAlpha": "./components/AcmeAlpha.tsx" to package.json "exports" and set import: '@acme/widgets/components/AcmeAlpha' in the doc.`,
+ `add "./components/AcmeBeta": "./components/AcmeBeta.tsx" to package.json "exports" and set import: '@acme/widgets/components/AcmeBeta' in the doc.`,
+ ]),
+ );
+ for (const fix of fixes) expect(fix).not.toContain('".":');
+ });
+});
+
+describe('type-only imports', () => {
+ it.each([
+ [
+ 'a statement-level import type',
+ {'./types': {types: './types.d.ts'}},
+ {'types.d.ts': 'export type AcmeWidgetSize = "sm" | "md";\n'},
+ "import type {AcmeWidgetSize} from '@acme/widgets/types';",
+ ],
+ [
+ 'an import whose every binding is an inline type',
+ {'./types': {types: './types.d.ts'}},
+ {'types.d.ts': 'export type AcmeWidgetSize = "sm" | "md";\n'},
+ "import {type AcmeWidgetSize} from '@acme/widgets/types';",
+ ],
+ [
+ 'a plain import of names the types file declares as types',
+ {'./types': {types: './types.d.ts'}},
+ {
+ 'types.d.ts':
+ 'export type AcmeWidgetSize = "sm" | "md";\ninterface AcmeTone {}\nexport {type AcmeTone as Tone};\n',
+ },
+ "import {AcmeWidgetSize, Tone} from '@acme/widgets/types';",
+ ],
+ [
+ 'a plain import of a declared type (wildcard entry)',
+ {'./types/*': {types: './types/*.d.ts'}},
+ {'types/size.d.ts': 'export type AcmeWidgetSize = "sm" | "md";\n'},
+ "import {AcmeWidgetSize} from '@acme/widgets/types/size';",
+ ],
+ [
+ 'a statement-level import type (types beside only require)',
+ {'./legacy': {types: './legacy.d.ts', require: './legacy.cjs'}},
+ {'legacy.d.ts': 'export type AcmeLegacy = string;\n'},
+ "import type {AcmeLegacy} from '@acme/widgets/legacy';",
+ ],
+ [
+ 'a plain import of a declared type (types beside only require)',
+ {'./legacy': {types: './legacy.d.ts', require: './legacy.cjs'}},
+ {'legacy.d.ts': 'export type AcmeLegacy = string;\n'},
+ "import {AcmeLegacy} from '@acme/widgets/legacy';",
+ ],
+ ])(
+ 'accepts %s from a subpath with a types target',
+ async (_label, entries, files, typeImport) => {
+ pkg(p => {
+ Object.assign(p.exports, entries);
+ });
+ for (const [file, text] of Object.entries(files)) write(file, text);
+ write(
+ 'components/AcmeWidget.doc.mjs',
+ DOC(
+ undefined,
+ `${typeImport}\\nimport {AcmeWidget} from '@acme/widgets/components/AcmeWidget';\\n<AcmeWidget />`,
+ ),
+ );
+ expect(await codes()).toEqual([]);
+ const report = (await validateLocalIntegration(dir)).publicImports;
+ expect(report?.unchecked).toEqual([]);
+ },
+ );
+
+ it('notes an import type whose only types target sits under require', async () => {
+ pkg(p => {
+ p.exports['./legacy'] = {
+ require: {types: './legacy.d.cts', default: './legacy.cjs'},
+ };
+ });
+ write('legacy.d.cts', 'export type AcmeLegacy = string;\n');
+ write(
+ 'components/AcmeWidget.doc.mjs',
+ DOC(
+ undefined,
+ "import type {AcmeLegacy} from '@acme/widgets/legacy';\\nimport {AcmeWidget} from '@acme/widgets/components/AcmeWidget';\\n<AcmeWidget />",
+ ),
+ );
+ expect(await codes()).not.toEqual([]);
+ });
+
+ it('lists a value import from a subpath with types beside only require as not checked', async () => {
+ pkg(p => {
+ p.exports['./legacy'] = {types: './legacy.d.ts', require: './legacy.cjs'};
+ });
+ write('legacy.d.ts', 'export declare const acmeLegacy: string;\n');
+ write(
+ 'components/AcmeWidget.doc.mjs',
+ DOC(
+ undefined,
+ "import {acmeLegacy} from '@acme/widgets/legacy';\\nimport {AcmeWidget} from '@acme/widgets/components/AcmeWidget';\\n<AcmeWidget />",
+ ),
+ );
+ expect(await codes()).toEqual([]);
+ const report = (await validateLocalIntegration(dir)).publicImports;
+ expect(report?.unchecked.map(u => u.specifier)).toEqual([
+ '@acme/widgets/legacy',
+ ]);
+ });
+
+ it('lists a value or unreadable import from a types-only subpath as not checked, never a note', async () => {
+ pkg(p => {
+ p.exports['./types'] = {types: './types.d.ts'};
+ p.exports['./gone'] = {types: './gone.d.ts'};
+ });
+ write(
+ 'types.d.ts',
+ 'export type AcmeWidgetSize = "sm";\nexport declare const ACME_SIZES: string[];\n',
+ );
+ write(
+ 'components/AcmeWidget.doc.mjs',
+ DOC(
+ undefined,
+ "import {type AcmeWidgetSize, ACME_SIZES} from '@acme/widgets/types';\\nimport {Gone} from '@acme/widgets/gone';\\nimport type {X} from '@acme/widgets/nope';\\n<AcmeWidget />",
+ ),
+ );
+ const notes = await found();
+ expect(notes.map(n => n.code)).toEqual(['example_import_not_exported']);
+ expect(notes[0].message).toContain('@acme/widgets/nope');
+ expect(notes[0].message).not.toContain('"default"');
+ const report = (await validateLocalIntegration(dir)).publicImports;
+ expect(report?.unchecked.map(u => u.specifier).sort()).toEqual([
+ '@acme/widgets/gone',
+ '@acme/widgets/types',
+ ]);
+ expect(
+ report?.unchecked.find(u => u.specifier === '@acme/widgets/types')
+ ?.reason,
+ ).toContain('ACME_SIZES');
+ });
+});
+
+describe('an empty exports map', () => {
+ it('names the missing subpath and adds only that entry', async () => {
+ pkg(p => {
+ p.exports = {};
+ });
+ const issue = (await found()).find(
+ i => i.code === 'component_import_not_exported',
+ );
+ expect(issue?.message).toContain(
+ 'package.json "exports" does not declare "./components/AcmeWidget"',
+ );
+ expect(issue?.message).toContain(
+ 'add "./components/AcmeWidget": "./components/AcmeWidget.tsx" to package.json "exports"',
+ );
+ expect(issue?.message).not.toContain('subpath map');
+ expect(subpathDeclaration({}, '.').state).toBe('missing');
+ expect(subpathDeclaration({}, './a').state).toBe('missing');
+ });
+});
+
+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-'));
+ try {
+ const put = (/** @type {string} */ rel, /** @type {string} */ text) => {
+ fs.mkdirSync(path.dirname(path.join(out, rel)), {recursive: true});
+ fs.writeFileSync(path.join(out, rel), text);
+ };
+ put(
+ 'package.json',
+ JSON.stringify({
+ name: '@acme/widgets',
+ version: '1.0.0',
+ type: 'module',
+ exports: {'./templates/account-card': './templates/account-card.tsx'},
+ }),
+ );
+ put(
+ 'astryx.integration.mjs',
+ "export default {templates: './templates'};\n",
+ );
+ put('templates/account-card.doc.mjs', BLOCK());
+ put(
+ 'templates/account-card.tsx',
+ "import {Button} from '@astryxdesign/core/src/Button';\nexport default function A() {\n return <Button />;\n}\n",
+ );
+ const run = spawnSync(
+ process.execPath,
+ [
+ path.join(CLI_ROOT, 'clients/cli/bin/astryx.mjs'),
+ '--json',
+ 'doctor',
+ 'integration',
+ 'validate',
+ ],
+ {cwd: out, encoding: 'utf-8', timeout: 60_000},
+ );
+ const {data} = JSON.parse(run.stdout);
+ expect(
+ data.issues.filter(
+ (/** @type {{code: string}} */ i) =>
+ i.code === 'template_private_import',
+ ),
+ ).toEqual([]);
+ expect(data.publicImports.unchecked).toEqual([
+ expect.objectContaining({
+ file: 'templates/account-card.tsx',
+ specifier: '@astryxdesign/core/src/Button',
+ }),
+ ]);
+ } finally {
+ fs.rmSync(out, {recursive: true, force: true});
+ }
+ }, 60_000);
+});
+
+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'},
+ }),
+ );
+ put(
+ 'packages/widgets/package.json',
+ JSON.stringify({
+ name: '@acme/widgets',
+ version: '1.0.0',
+ type: 'module',
+ exports: {'./templates/account-card': './templates/account-card.tsx'},
+ }),
+ );
+ put(
+ 'packages/widgets/astryx.integration.mjs',
+ "export default {templates: './templates'};\n",
+ );
+ put('packages/widgets/templates/account-card.doc.mjs', BLOCK());
+ put(
+ 'packages/widgets/templates/account-card.tsx',
+ "import {Button} from '@astryxdesign/core/Button';\nexport default function A() {\n return <Button />;\n}\n",
+ );
+ const result = await validateIntegration(undefined, {
+ cwd: path.join(root, 'packages/widgets'),
+ });
+ expect(
+ (result.data.notes ?? []).filter(
+ i => i.code === 'template_private_import',
+ ),
+ ).toEqual([]);
+ expect(result.data.publicImports?.unchecked).toEqual([
+ expect.objectContaining({
+ file: 'templates/account-card.tsx',
+ specifier: '@astryxdesign/core/Button',
+ }),
+ ]);
+ } finally {
+ fs.rmSync(root, {recursive: true, force: true});
+ }
+ });
+
+ it('with no package name, runs only the checks that need none and lists the rest as not checked', async () => {
+ pkg(p => delete p.name);
+ write(
+ 'templates/account-card.tsx',
+ "import {AcmeWidget} from '../components/AcmeWidget';\nimport {X} from '@acme/widgets/nope';\nexport default function C() {\n return <AcmeWidget label={X} />;\n}\n",
+ );
+ const result = await validateIntegration(undefined, {cwd: dir});
+ expect(await codes()).toEqual(['template_import_outside_root']);
+ expect(result.data.publicImports?.status).toBe('checked');
+ expect(result.data.publicImports?.unchecked).toContainEqual(
+ expect.objectContaining({
+ file: 'package.json',
+ reason: expect.stringContaining('no "name"'),
+ }),
+ );
+ // Nothing from the public-import check fails `integration check
+ // --strict`: no skip, no warning (other checks may report the missing
+ // name themselves).
+ const {warnings, skipped} = strictIssues('validate', result);
+ expect(
+ [...warnings, ...skipped].filter(
+ each => CODES.has(each.code) || each.code === 'public_imports_skipped',
+ ),
+ ).toEqual([]);
+ });
+});
diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjs
index 8192b13bef..3042294d06 100644
--- a/packages/cli/foundation/response/response-types.doc.mjs
+++ b/packages/cli/foundation/response/response-types.doc.mjs
@@ -338,7 +338,7 @@ export const doc = {
{
value: 'integration.validate',
description:
- 'The validation result: validated (false when nothing was validated: with no package.json the issues list carries one no_package error so the command exits 1, and with a package.json but no integration manifest the issues list is empty and proves nothing), the package name and version (both null when validated is false) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning | error, message, fix?, file?, line?} (fix: the change that resolves it; file and line: where, relative to the package), and notes when there are any: {code, message} information that fails nothing, such as invalid_cli_command for a malformed cliCommand, 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_provider_id, source_without_component_doc where a doc and its source still pair), and doc_name_mismatch and unknown_block_component, until they become warnings in the next minor release. A runner_command note lists each Astryx command a topic writes with a package runner (its file, line and the bare command to write). When the manifest loads, docTypes checks each doc against its published authoring type: status (checked | skipped), reason, typescript, docs, findings (all warnings, each naming the field and a fix), unchecked, and fixtures (test fixture docs not checked). When the manifest loads, 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, 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).',
+ 'The validation result: validated (false when nothing was validated: with no package.json the issues list carries one no_package error so the command exits 1, and with a package.json but no integration manifest the issues list is empty and proves nothing), the package name and version (both null when validated is false) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning | error, message, fix?, file?, line?} (fix: the change that resolves it; file and line: where, relative to the package), and notes when there are any: {code, message} information that fails nothing, such as invalid_cli_command for a malformed cliCommand, 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_provider_id, source_without_component_doc where a doc and its source still pair), and doc_name_mismatch and unknown_block_component, until they become warnings in the next minor release. A runner_command note lists each Astryx command a topic writes with a package runner (its file, line and the bare command to write). When the manifest loads, docTypes checks each doc against its published authoring type: status (checked | skipped), reason, typescript, docs, findings (all warnings, each naming the field and a fix), unchecked, and fixtures (test fixture docs not checked). When the manifest loads, 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, 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 also a note (its fix in the message), listed only and failing --strict from the next minor. publicImports ({status: checked, findings: [], unchecked}) lists each import the check could not judge as {file, specifier, reason}; never counted or failed on.',
},
{
value: 'integration.template-conflicts',
diff --git a/packages/cli/test/integration-check-failures.json b/packages/cli/test/integration-check-failures.json
index 619d74a354..56652fec0b 100644
--- a/packages/cli/test/integration-check-failures.json
+++ b/packages/cli/test/integration-check-failures.json
@@ -1,7 +1,13 @@
{
"checks": ["validate", "components", "templates", "docs"],
"results": {
- "validate": ["blockComponents", "docNames", "docTypes", "issues"],
+ "validate": [
+ "blockComponents",
+ "docNames",
+ "docTypes",
+ "issues",
+ "publicImports"
+ ],
"components": ["conflicts", "issues", "propDrift"],
"templates": ["conflicts", "issues"],
"docs": ["copiedPassages", "findings", "fluff", "issues", "strayPointers"]
@@ -10,7 +16,8 @@
"blockComponents": "block_components_skipped",
"docNames": "doc_names_skipped",
"docTypes": "doc_types_skipped",
- "propDrift": "prop_drift_skipped"
+ "propDrift": "prop_drift_skipped",
+ "publicImports": "public_imports_skipped"
},
"codes": [
"ambiguous_component_replacement",
@@ -60,6 +67,7 @@
"package_not_found",
"prop_drift_skipped",
"prop_types_skipped",
+ "public_imports_skipped",
"required_mismatch",
"root_outside_package",
"runner_command",