An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): report one import specifier for an integration component (#6203)
Joey6443c65130b1
diff --git a/.changeset/one-import-specifier-per-component.md b/.changeset/one-import-specifier-per-component.mdnew file mode 100644index 0000000000..e8bdce66b7--- /dev/null+++ b/.changeset/one-import-specifier-per-component.md@@ -0,0 +1,6 @@+---+'@astryxdesign/cli': patch+---++[fix] `component` and `search` now report the same import specifier for an integration component, resolved once in `foundation/discovery/component-discovery.mjs`. `search` previously returned the bare package name, which does not resolve for a package whose components are exported behind subpaths.+@josephfarinadiff --git a/packages/cli/api/component/_adapter.mjs b/packages/cli/api/component/_adapter.mjsindex 06b3877e5c..b3075d9ca6 100644--- a/packages/cli/api/component/_adapter.mjs+++ b/packages/cli/api/component/_adapter.mjs@@ -18,8 +18,6 @@* deduped, so each leaf stays a thin projection.*/-import * as fs from 'node:fs';-import * as path from 'node:path';import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';import {findCoreDir, discoverExternalPackages} from '../../foundation/fs/paths.mjs';import {@@ -31,6 +29,7 @@ import {findIntegrationComponentDoc,findIntegrationComponentSource,resolveImportPath,+ resolveIntegrationImportPath as resolveIntegrationImport,} from '../../foundation/discovery/component-discovery.mjs';import {Project} from '../../foundation/config/project.mjs';import {loadDocs} from '../../foundation/discovery/component-loader.mjs';@@ -388,39 +387,26 @@ export function withOwnership(docs, owner, componentName, coreDir) {}/**- * Resolve the specifier an integration component is imported from, against the- * owning package's `exports` map.+ * Resolve the specifier an integration component is imported from.*- * A component lives in a directory that need not share its name — several- * components can be exported from one entry point — so the specifier has to- * come from the directory the doc file sits in, checked against `exports`,- * rather than from the component name. Falls back to the package root when the- * directory is not an exported subpath, matching what a consumer would have to- * write by hand.+ * Thin adapter over the shared resolver in foundation, which `search` also+ * uses; the two surfaces have to report the same specifier for the same+ * component.** @param {OwnershipSubject} owner* @param {string} componentName* @returns {string}*/function resolveIntegrationImportPath(owner, componentName) {- const packageDir = owner.integration?.__packageDir;- const directory = owner.docPath- ? path.basename(path.dirname(owner.docPath))- : componentName;- if (!packageDir) {- return owner.package;- }- try {- const manifest = JSON.parse(- fs.readFileSync(path.join(packageDir, 'package.json'), 'utf-8'),- );- if (manifest.exports?.[`./${directory}`]) {- return `${owner.package}/${directory}`;- }- } catch {- // An unreadable or malformed manifest is not worth failing a lookup over.- }- return owner.package;+ return resolveIntegrationImport(+ {+ exportsMap: owner.integration?.__packageExports,+ packageDir: owner.integration?.__packageDir,+ docPath: owner.docPath,+ packageName: owner.package,+ },+ componentName,+ );}/**diff --git a/packages/cli/api/component/integration-import-agreement.test.mjs b/packages/cli/api/component/integration-import-agreement.test.mjsnew file mode 100644index 0000000000..94f6603af7--- /dev/null+++ b/packages/cli/api/component/integration-import-agreement.test.mjs@@ -0,0 +1,318 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The import specifier an integration component is reported under has to+ * be the SAME at every surface, and it has to resolve.+ *+ * `component` reports it as ownership metadata and `search` reports it on every+ * hit. Each used to resolve it independently, and they disagreed: `component`+ * honored a doc-authored `import` and otherwise derived the subpath from the+ * doc's directory against the owning package's `exports`, while `search` handed+ * back the bare package name — a specifier that does not resolve for a package+ * whose components live behind subpaths. An agent that searched and then+ * imported what it was told got a broken file.+ *+ * The two now share one resolver and one precedence rule, so the agreement is+ * structural. These tests pin the property rather than the implementation: ask+ * both surfaces about the same component and require the same answer, across+ * every shape a real package's `exports` takes.+ *+ * Fixtures live under a repo-local temp dir, not /tmp, because Vite refuses to+ * dynamically import a module from outside the project root.+ */++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {component} from './component.mjs';+import {search} from '../search/search.mjs';+import {resolveIntegrationImportPath} from '../../foundation/discovery/component-discovery.mjs';++const SLOW = 30_000;++let tmpDir;++/**+ * A consumer project with one configured integration that ships a single+ * component, `AcmeCarousel`, in a directory named after the concept rather+ * than after the component — the shape real packages use when one entry point+ * exports several components, and the case the bare-package answer got wrong.+ *+ * @param {object} [options]+ * @param {Record<string, string>} [options.exports] the owning package's+ * `exports` map; omit it for a package that publishes no subpaths.+ * @param {string} [options.docImport] an `import` the component's doc states+ * for itself, which is canonical and must win over any resolved subpath.+ */+function scaffold({exports: exportsMap, docImport} = {}) {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: 'consumer', version: '1.0.0'}),+ );+ fs.writeFileSync(+ path.join(tmpDir, 'astryx.config.mjs'),+ "export default {integrations: ['@acme/widgets']};\n",+ );++ const pkgDir = path.join(tmpDir, 'node_modules', '@acme', 'widgets');+ const componentDir = path.join(pkgDir, 'src', 'Carousel');+ fs.mkdirSync(componentDir, {recursive: true});++ fs.writeFileSync(+ path.join(pkgDir, 'package.json'),+ JSON.stringify({+ name: '@acme/widgets',+ version: '1.0.0',+ ...(exportsMap ? {exports: exportsMap} : {}),+ }),+ );+ fs.writeFileSync(+ path.join(pkgDir, 'astryx.integration.mjs'),+ "export default {components: './src'};\n",+ );+ fs.writeFileSync(+ path.join(componentDir, 'AcmeCarousel.tsx'),+ 'export const AcmeCarousel = () => null;\n',+ );+ fs.writeFileSync(+ path.join(componentDir, 'AcmeCarousel.doc.mjs'),+ `export const docs = ${JSON.stringify(+ {+ type: 'component',+ name: 'AcmeCarousel',+ displayName: 'Acme Carousel',+ keywords: ['carousel', 'slides'],+ usage: {description: 'A carousel that cycles through slides.'},+ props: [],+ ...(docImport ? {import: docImport} : {}),+ },+ null,+ 2,+ )};\n`,+ );+}++/** The import `search` reports for a named component, or null. */+function searchImportFor(result, name) {+ for (const group of Object.values(result.data ?? {})) {+ if (!Array.isArray(group)) continue;+ const hit = group.find(entry => entry?.name === name);+ if (hit) return hit.import ?? null;+ }+ return null;+}++/** Both surfaces' answer for AcmeCarousel, as `{detail, found}`. */+async function bothSurfaces() {+ const detail = await component('AcmeCarousel', {cwd: tmpDir});+ const found = await search('carousel', {cwd: tmpDir});+ return {detail: detail.data.import, found: searchImportFor(found, 'AcmeCarousel')};+}++const SUBPATH_EXPORTS = {+ '.': './src/index.js',+ './Carousel': './src/Carousel/index.js',+};++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-import-agreement-test-'));+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('integration component import specifiers', () => {+ it(+ 'component and search report the same import for the same component',+ async () => {+ scaffold({exports: SUBPATH_EXPORTS});+ const {detail, found} = await bothSurfaces();++ expect(detail).toBe('@acme/widgets/Carousel');+ expect(found).toBe(detail);+ },+ SLOW,+ );++ it(+ 'neither surface reports the bare package when a subpath is exported',+ async () => {+ scaffold({exports: SUBPATH_EXPORTS});+ const {detail, found} = await bothSurfaces();++ expect(detail).not.toBe('@acme/widgets');+ expect(found).not.toBe('@acme/widgets');+ },+ SLOW,+ );++ it(+ 'both fall back to the package root when it exports no matching subpath',+ async () => {+ scaffold();+ const {detail, found} = await bothSurfaces();++ // The bare package is the honest answer here: it is what a consumer+ // would have to write by hand. What matters is that both agree on it.+ expect(detail).toBe('@acme/widgets');+ expect(found).toBe('@acme/widgets');+ },+ SLOW,+ );++ it(+ 'a doc-authored import wins at both surfaces, over any resolved subpath',+ async () => {+ // The alias case: the package canonically publishes this component under+ // a name that is not its directory, and says so in its doc. Resolving the+ // directory would produce `/Carousel`, which is why the two surfaces have+ // to share the precedence rule and not just the resolver.+ scaffold({exports: SUBPATH_EXPORTS, docImport: '@acme/widgets/Alias'});+ const {detail, found} = await bothSurfaces();++ expect(detail).toBe('@acme/widgets/Alias');+ expect(found).toBe(detail);+ },+ SLOW,+ );++ it(+ 'a doc-authored import is honored even with no exports map at all',+ async () => {+ scaffold({docImport: '@acme/widgets/Alias'});+ const {detail, found} = await bothSurfaces();++ expect(detail).toBe('@acme/widgets/Alias');+ expect(found).toBe(detail);+ },+ SLOW,+ );++ it(+ 'a wildcard exports map resolves to the exported subpath at both surfaces',+ async () => {+ // `./*` publishes `./Carousel` exactly as a literal key would, so the+ // subpath is the correct answer. An earlier version of this test asserted+ // only that the two surfaces AGREED, and both agreed on the bare package+ // — a specifier that need not resolve at all here, since this package+ // publishes no `.` export. Agreement is necessary and not sufficient.+ scaffold({exports: {'./*': './src/*/index.js'}});+ const {detail, found} = await bothSurfaces();++ expect(detail).toBe('@acme/widgets/Carousel');+ expect(found).toBe(detail);+ },+ SLOW,+ );++ it(+ 'a wildcard whose target is null does not publish the subpath',+ async () => {+ // `null` blocks a subpath rather than publishing it, so the honest answer+ // is the package root at both surfaces.+ scaffold({exports: {'.': './src/index.js', './*': null}});+ const {detail, found} = await bothSurfaces();++ expect(detail).toBe('@acme/widgets');+ expect(found).toBe(detail);+ },+ SLOW,+ );++ it(+ 'a prefixed wildcard only matches the subpaths it covers',+ async () => {+ // `./components/*` does not cover `./Carousel`, so this falls back.+ scaffold({exports: {'.': './src/index.js', './components/*': './src/*/index.js'}});+ const {detail, found} = await bothSurfaces();++ expect(detail).toBe('@acme/widgets');+ expect(found).toBe(detail);+ },+ SLOW,+ );++ it(+ 'an exact key still wins where a wildcard would also match',+ async () => {+ scaffold({+ exports: {+ '.': './src/index.js',+ './Carousel': './src/Carousel/index.js',+ './*': './src/*/index.js',+ },+ });+ const {detail, found} = await bothSurfaces();++ expect(detail).toBe('@acme/widgets/Carousel');+ expect(found).toBe(detail);+ },+ SLOW,+ );++ it(+ 'one matching pattern among several is enough',+ async () => {+ scaffold({+ exports: {+ '.': './src/index.js',+ './blocks/*': './src/blocks/*.js',+ './*': './src/*/index.js',+ './themes/*': './themes/*.css',+ },+ });+ const {detail, found} = await bothSurfaces();++ expect(detail).toBe('@acme/widgets/Carousel');+ expect(found).toBe(detail);+ },+ SLOW,+ );++ it(+ 'a conditional export object still counts as published',+ async () => {+ // The target may be a conditions object rather than a string; what+ // matters for a specifier is that the subpath is published at all.+ scaffold({+ exports: {+ '.': './src/index.js',+ './Carousel': {import: './src/Carousel/index.js', require: './cjs/Carousel.js'},+ },+ });+ const {detail, found} = await bothSurfaces();++ expect(detail).toBe('@acme/widgets/Carousel');+ expect(found).toBe(detail);+ },+ SLOW,+ );++ it('resolves from disk for a record that carries no parsed exports map', () => {+ // `loadIntegrations` parses the map onto every integration it loads, but a+ // record built by hand — as several tests and callers do — has no such+ // field. Resolution must read the manifest rather than quietly reporting+ // the bare package, because a silent degradation is how the original bug+ // reached users. `undefined` means "nobody parsed it"; `null` means the+ // loader looked and there was none.+ scaffold({exports: SUBPATH_EXPORTS});+ const pkgDir = path.join(tmpDir, 'node_modules', '@acme', 'widgets');+ const docPath = path.join(pkgDir, 'src', 'Carousel', 'AcmeCarousel.doc.mjs');++ expect(+ resolveIntegrationImportPath(+ {packageDir: pkgDir, docPath, packageName: '@acme/widgets'},+ 'AcmeCarousel',+ ),+ ).toBe('@acme/widgets/Carousel');++ // A parsed `null` is an answer, not a gap: it must not fall back to a read.+ expect(+ resolveIntegrationImportPath(+ {exportsMap: null, packageDir: pkgDir, docPath, packageName: '@acme/widgets'},+ 'AcmeCarousel',+ ),+ ).toBe('@acme/widgets');+ });+});diff --git a/packages/cli/api/search/search.mjs b/packages/cli/api/search/search.mjsindex 0ece9a6d2b..63ed69e880 100644--- a/packages/cli/api/search/search.mjs+++ b/packages/cli/api/search/search.mjs@@ -57,6 +57,7 @@ import {discoverIntegrationComponents,findComponentReadme,resolveImportPath,+ resolveIntegrationImportPath,} from '../../foundation/discovery/component-discovery.mjs';import {discoverHooks, findHookDoc} from '../../foundation/discovery/hook-discovery.mjs';import {loadIntegrationsSafely} from '../component/_adapter.mjs';@@ -552,7 +553,24 @@ async function gatherIntegrationComponents(cwd) {keywords: doc && Array.isArray(doc.keywords) ? doc.keywords : [],description: doc ? doc.usage?.description || doc.description || '' : '',guidance: guidanceFrom(doc),- _import: rec.package,+ // Exactly what `component` reports: a doc may state its own specifier+ // (one entry point exporting several components), and only when it+ // does not do we resolve the subpath against the owning package's+ // exports — read off the integration, which the loader already parsed.+ // Reporting the bare package name here handed out a path that does not+ // resolve, and disagreed with what `component <Name>` said about the+ // very same component.+ _import:+ doc?.import ??+ resolveIntegrationImportPath(+ {+ exportsMap: integration.__packageExports,+ packageDir: integration.__packageDir,+ docPath: rec.docPath,+ packageName: rec.package,+ },+ rec.name,+ ),});}}diff --git a/packages/cli/foundation/discovery/component-discovery.mjs b/packages/cli/foundation/discovery/component-discovery.mjsindex 0cf9e832ba..f77f985d82 100644--- a/packages/cli/foundation/discovery/component-discovery.mjs+++ b/packages/cli/foundation/discovery/component-discovery.mjs@@ -395,6 +395,102 @@ export function resolveImportPath(coreDir, componentName) {return '@astryxdesign/core';}+/**+ * Does a package's `exports` map publish this subpath?+ *+ * Node matches a subpath either by an exact key or by a PATTERN key holding a+ * single `*`, which stands for any (possibly empty) run of characters — so+ * `./*` publishes `./Carousel` just as surely as a literal `./Carousel` key+ * does. A key whose target is `null` blocks the subpath instead of publishing+ * it, and a package with no map at all publishes nothing by subpath.+ *+ * Exact-key-only matching is why this is a function rather than a lookup: it+ * reported the bare package for every wildcard package, which is a specifier+ * that need not resolve at all when the package has no `.` export.+ *+ * @param {Record<string, unknown>|null|undefined} exportsMap+ * @param {string} subpath e.g. `./Carousel`+ * @returns {boolean}+ */+function exportsPublish(exportsMap, subpath) {+ if (!exportsMap || typeof exportsMap !== 'object') return false;+ if (subpath in exportsMap) return exportsMap[subpath] != null;+ for (const [key, target] of Object.entries(exportsMap)) {+ const star = key.indexOf('*');+ if (star === -1) continue;+ // One `*` per key, per the spec; a second is not a pattern.+ if (key.indexOf('*', star + 1) !== -1) continue;+ const prefix = key.slice(0, star);+ const suffix = key.slice(star + 1);+ if (+ subpath.length >= prefix.length + suffix.length &&+ subpath.startsWith(prefix) &&+ subpath.endsWith(suffix)+ ) {+ return target != null;+ }+ }+ return false;+}++/**+ * Resolve the specifier an integration component is imported from, against the+ * owning package's `exports` map.+ *+ * A component lives in a directory that need not share its name — several+ * components can be exported from one entry point — so the specifier has to+ * come from the directory the doc file sits in, checked against `exports`,+ * rather than from the component name. Falls back to the package root when the+ * package does not publish that subpath, matching what a consumer would have+ * to write by hand.+ *+ * Lives here, beside {@link resolveImportPath}, because more than one surface+ * answers "where is this imported from" and they have to agree: `component`+ * reports it as ownership metadata and `search` reports it on every hit. When+ * each resolved it for itself the two disagreed, and an import specifier that+ * does not resolve is worse than no answer.+ *+ * `exportsMap` is the map `loadIntegrations` already parsed onto the loaded+ * integration, so the common path reads no manifest at all. `undefined` means+ * the caller has no parsed map — a record built by hand rather than by the+ * loader — and only then is the manifest read here. `null` means the loader+ * looked and the package has no `exports`, which is an answer, not a gap: it+ * must not trigger a read. Resolution that depended on every producer of a+ * record remembering to populate a field would degrade silently, and silently+ * is how this bug got here.+ *+ * @param {{exportsMap?: Record<string, unknown>|null, packageDir?: string, docPath?: string|null, packageName: string}} owner+ * @param {string} componentName+ * @returns {string}+ */+export function resolveIntegrationImportPath(owner, componentName) {+ const {exportsMap, packageDir, docPath, packageName} = owner;+ const map = exportsMap === undefined ? readPackageExports(packageDir) : exportsMap;+ const directory = docPath ? path.basename(path.dirname(docPath)) : componentName;+ return exportsPublish(map, `./${directory}`) ? `${packageName}/${directory}` : packageName;+}++/**+ * Read a package's `exports` map from disk. The fallback for a loaded-+ * integration record that carries no parsed map; {@link loadIntegrations}+ * populates one for every integration it loads.+ *+ * @param {string|undefined} packageDir+ * @returns {Record<string, unknown>|null}+ */+function readPackageExports(packageDir) {+ if (!packageDir) return null;+ try {+ const manifest = JSON.parse(+ fs.readFileSync(path.join(packageDir, 'package.json'), 'utf-8'),+ );+ return manifest.exports ?? null;+ } catch {+ // An unreadable or malformed manifest is not worth failing a lookup over.+ return null;+ }+}+// ── External package discovery ───────────────────────────────────────/**diff --git a/packages/cli/foundation/integrations/integrations.mjs b/packages/cli/foundation/integrations/integrations.mjsindex 1f6b9ec62a..a6014a0d8d 100644--- a/packages/cli/foundation/integrations/integrations.mjs+++ b/packages/cli/foundation/integrations/integrations.mjs@@ -41,6 +41,9 @@ import {importUserModule, findPresentFiles} from '../fs/module-loader.mjs';* failure; other manifest contributions remain available* @property {string} __spec* @property {string} __packageDir+ * @property {Record<string, unknown>|null} [__packageExports] the owning+ * package's `exports` map, kept from the package.json this loader already+ * parsed so import resolution does not read it a second time* @property {string} __manifestFile* @property {string} [__loadError] set when the manifest failed to load/validate;* such an integration contributes nothing and is surfaced via Project.issues()@@ -287,6 +290,7 @@ export async function loadIntegrations(__debug: debugHandler,__spec: spec,__packageDir: packageDir,+ __packageExports: pkg.exports ?? null,__manifestFile: manifestFile,});}