An open source design system that's fully customizable and agent ready
TypeScript
[CLI] Discover results name their source package and tolerate typos (#7147)
Joey33b8bfe66be7
diff --git a/.changeset/discover-provenance-and-typo-tolerance.md b/.changeset/discover-provenance-and-typo-tolerance.mdnew file mode 100644index 0000000000..9928e6ff4a--- /dev/null+++ b/.changeset/discover-provenance-and-typo-tolerance.md@@ -0,0 +1,17 @@+---+'@astryxdesign/cli': patch+---++[fix] Discover results name their source package and tolerate typos.++@josephfarina++Every `discover` JSON result now names its package per the provenance rule:+single-artifact responses (`discover.detail`, `discover.detail.doc`,+`discover.item`) carry `package` in the envelope, and list entries+(`discover.list`, and each entry of its `meta.available`) carry `package`. Text output matches: an opened doc prints its `package:` line on stdout.++`discover <words>` now has the same typo tolerance as `search`: a near-miss+name (edit distance 1–3, with minimum-length guards) returns results instead+of "not found". Previously `discover Geodetics` said "not found" while+`search Geodetics` found `geodesic`.diff --git a/packages/cli/README.md b/packages/cli/README.mdindex ccb184f020..0dded723a1 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -489,10 +489,10 @@ Every response has a `type` discriminant. The full set is below (generated from| `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.list` | What the project has, the integrations it loads and the official packages it declares, official packages first (package, the npm package and always equal to name; 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 its package and 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: its package (the npm package the result is about), 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, plus package, the npm package that owns the component. |+| `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. The envelope's package names the same 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. |diff --git a/packages/cli/api/discover/_adapter.mjs b/packages/cli/api/discover/_adapter.mjsindex 9a4ce67a0b..2e5ab9aad6 100644--- a/packages/cli/api/discover/_adapter.mjs+++ b/packages/cli/api/discover/_adapter.mjs@@ -27,10 +27,7 @@ import {import {isOutsideProject} from '../../foundation/env/project-scope.mjs';import {projectAddCommand} from '../../foundation/release/notices.mjs';import {hostedRun} from '../../foundation/runtime/package-root.mjs';-import {- scanAllPackages,- findComponentInPackages,-} from './_package-scanner.mjs';+import {scanAllPackages, findComponentInPackages} from './_package-scanner.mjs';import {loadDocs} from '../../foundation/discovery/component-loader.mjs';import {collectIdentities} from '../../foundation/integrations/contribution-inventory.mjs';import {detectPackageManager} from '../../foundation/env/package-manager.mjs';@@ -146,8 +143,7 @@ function validateDocs(docs) {return 'docs.name is missing or not a string';if (!d.usage || typeof d.usage.description !== 'string')return 'docs.usage.description is missing or not a string';- if (d.props && !Array.isArray(d.props))- return 'docs.props must be an array';+ if (d.props && !Array.isArray(d.props)) return 'docs.props must be an array';if (d.components && !Array.isArray(d.components))return 'docs.components must be an array';if (d.usage?.bestPractices && !Array.isArray(d.usage.bestPractices))@@ -286,6 +282,7 @@ export async function computerAvailableEntries(project, installed, declared) {const have = new Set([...installed.map(pkg => pkg.name), ...declared]);return (await availableComputerIntegrations(cwd, have)).map(c => ({name: c.name,+ package: c.name,components: [],...(c.version ? {version: c.version} : {}),...(c.description ? {description: c.description} : {}),@@ -597,7 +594,10 @@ async function callOwnSources(project, request = {}, options = {}) {}for (const integration of project?.loadedIntegrations ?? []) {if (integration.__discoverError) {- origins.push({from: integration.name, error: integration.__discoverError});+ origins.push({+ from: integration.name,+ error: integration.__discoverError,+ });} else if (integration.__discover) {origins.push({from: integration.name, source: integration.__discover});}@@ -617,7 +617,10 @@ async function callOwnSources(project, request = {}, options = {}) {/** @type {Set<string>} */const seen = new Set();const ask = request.package- ? {package: request.package, ...(request.version ? {version: request.version} : {})}+ ? {+ package: request.package,+ ...(request.version ? {version: request.version} : {}),+ }: {};for (const {from, key = from, source, error} of origins) {if (source == null) {@@ -645,7 +648,12 @@ async function callOwnSources(project, request = {}, options = {}) {const message = err instanceof Error ? err.message : String(err);const saved = readSavedCopy(file, label);if (saved == null) {- result.sources.push({name: from, from, status: 'failed', error: message});+ result.sources.push({+ name: from,+ from,+ status: 'failed',+ error: message,+ });continue;}catalog = saved.catalog;@@ -940,6 +948,7 @@ export function toEntry(pkg) {/** @type {Record<string, unknown>} */const entry = {name: pkg.name,+ package: pkg.name,category: pkg.category,components: pkg.components,version: pkg.version,@@ -979,7 +988,10 @@ export async function loadValidatedDoc(result, {lang, zh}) {try {docs = await loadDocs(result.docPath,- /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({zh, lang}),+ /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({+ zh,+ lang,+ }),);} catch (e) {throw new AstryxError(diff --git a/packages/cli/api/discover/_catalog-view.mjs b/packages/cli/api/discover/_catalog-view.mjsindex 2d74f707d1..a3a96e86a2 100644--- a/packages/cli/api/discover/_catalog-view.mjs+++ b/packages/cli/api/discover/_catalog-view.mjs@@ -102,6 +102,7 @@ export function catalogEntry(pkg, version) {const {components, ...others} = kindLists(pkg.contributions);return {name: pkg.package,+ package: pkg.package,category: pkg.package,components,...(version ? {version} : {}),diff --git a/packages/cli/api/discover/_catalog-view.test.mjs b/packages/cli/api/discover/_catalog-view.test.mjsindex 1d3ad2be55..8ede651767 100644--- a/packages/cli/api/discover/_catalog-view.test.mjs+++ b/packages/cli/api/discover/_catalog-view.test.mjs@@ -74,6 +74,7 @@ describe('availableEntries', () => {it('describes an entry the way an installed one is described', () => {expect(availableEntries(CATALOG, [], new Set())[1]).toEqual({name: '@acme/charts',+ package: '@acme/charts',components: [],version: '2.0.0',themes: ['ocean'],diff --git a/packages/cli/api/discover/detail/detail.mjs b/packages/cli/api/discover/detail/detail.mjsindex e23123e140..531818ad3a 100644--- a/packages/cli/api/discover/detail/detail.mjs+++ b/packages/cli/api/discover/detail/detail.mjs@@ -80,6 +80,7 @@ export function detail(packages, name, options = {}) {if (catalog) data.versions = catalog.versions;return {type: 'discover.detail',+ package: String(data.name),data: /** @type {import('../discover.type.mjs').DiscoverDetailResponse['data']} */ (data),diff --git a/packages/cli/api/discover/detail/detail.test.mjs b/packages/cli/api/discover/detail/detail.test.mjsindex ba50809764..93c4ea8f3e 100644--- a/packages/cli/api/discover/detail/detail.test.mjs+++ b/packages/cli/api/discover/detail/detail.test.mjs@@ -31,8 +31,10 @@ describe('discover.detail leaf', () => {it('projects the matched package into a detail entry', () => {const res = detail(PACKAGES, '@acme/widgets');expect(res.type).toBe('discover.detail');+ expect(res.package).toBe('@acme/widgets');expect(res.data).toEqual({name: '@acme/widgets',+ package: '@acme/widgets',category: '@acme/widgets',components: ['Alpha', 'Beta'],version: '1.2.3',@@ -81,6 +83,7 @@ describe('discover.detail leaf with a discover source', () => {it('describes a package the project does not have, with the command that adds it', () => {expect(detail(PACKAGES, '@acme/charts', {catalog, add}).data).toEqual({name: '@acme/charts',+ package: '@acme/charts',category: '@acme/charts',components: ['Chart'],version: '2.0.0',diff --git a/packages/cli/api/discover/detail/doc/doc.mjs b/packages/cli/api/discover/detail/doc/doc.mjsindex 22832c18ec..f9fb60099e 100644--- a/packages/cli/api/discover/detail/doc/doc.mjs+++ b/packages/cli/api/discover/detail/doc/doc.mjs@@ -35,7 +35,11 @@ export async function docFromResult(result, opts) {{type: 'component.detail', package: result.pkg.name, data},process.cwd(),);- return {type: 'discover.detail.doc', data: linked.data};+ return {+ type: 'discover.detail.doc',+ package: result.pkg.name,+ data: linked.data,+ };}/**diff --git a/packages/cli/api/discover/detail/doc/doc.test.mjs b/packages/cli/api/discover/detail/doc/doc.test.mjsindex c5d583683b..320ce93acd 100644--- a/packages/cli/api/discover/detail/doc/doc.test.mjs+++ b/packages/cli/api/discover/detail/doc/doc.test.mjs@@ -86,6 +86,7 @@ describe('discover.detail.doc leaf', () => {);expect(res).toEqual({type: 'discover.detail.doc',+ package: '@acme/widgets',data: {name: 'Beta', usage: {description: 'Beta component'}, props: []},});});diff --git a/packages/cli/api/discover/detail/item/item.mjs b/packages/cli/api/discover/detail/item/item.mjsindex 74038ce68f..ea6ea5c134 100644--- a/packages/cli/api/discover/detail/item/item.mjs+++ b/packages/cli/api/discover/detail/item/item.mjs@@ -39,6 +39,7 @@ export function item(packages, packageName, itemName, options = {}) {if (Array.isArray(names) && names.includes(itemName)) {return {type: 'discover.item',+ package: packageName,data: {package: packageName,...(pkg.version ? {version: pkg.version} : {}),@@ -59,6 +60,7 @@ export function item(packages, packageName, itemName, options = {}) {const shown = version ?? defaultVersion(catalog);return {type: 'discover.item',+ package: packageName,data: {package: packageName,...(shown ? {version: shown} : {}),diff --git a/packages/cli/api/discover/detail/item/item.test.mjs b/packages/cli/api/discover/detail/item/item.test.mjsindex f9cb576321..0d2e544b41 100644--- a/packages/cli/api/discover/detail/item/item.test.mjs+++ b/packages/cli/api/discover/detail/item/item.test.mjs@@ -38,6 +38,7 @@ describe('discover.item leaf', () => {it("finds an installed package's own template, doc, theme, or codemod", () => {expect(item(PACKAGES, '@acme/widgets', 'pages/Home')).toEqual({type: 'discover.item',+ package: '@acme/widgets',data: {package: '@acme/widgets',version: '1.2.3',@@ -53,6 +54,7 @@ describe('discover.item leaf', () => {item(PACKAGES, '@acme/charts', 'pages/report', {catalog: CATALOG, add}),).toEqual({type: 'discover.item',+ package: '@acme/charts',data: {package: '@acme/charts',version: '2.0.0',diff --git a/packages/cli/api/discover/discover.doc.mjs b/packages/cli/api/discover/discover.doc.mjsindex 34074e9fa0..bd5d93c332 100644--- a/packages/cli/api/discover/discover.doc.mjs+++ b/packages/cli/api/discover/discover.doc.mjs@@ -91,22 +91,22 @@ export const doc = {{type: 'discover.list',description:- 'What the project has: the integrations it loads and the official packages it declares (name, category, components, version, and a list per other kind they add), official packages first. meta.available lists what the project could add, official packages first, each with the command that adds it; inside a project, an integration installed for the computer that the project does not install is listed there too, with source `installed for this computer` and the install command for the project in `install`. meta.sources reports each source, the official list last. When it lists no integration it carries meta.configured.',+ 'What the project has: the integrations it loads and the official packages it declares (package, the npm package and always equal to name; name, category, components, version, and a list per other kind they add), official packages first. meta.available lists what the project could add, official packages first, each with its package and the command that adds it; inside a project, an integration installed for the computer that the project does not install is listed there too, with source `installed for this computer` and the install command for the project in `install`. meta.sources reports each source, the official list last. When it lists no integration it carries meta.configured.',},{type: 'discover.detail',description:- "One package: what the shown version adds, whether the project has it, its versions and latest release when a source knows them, and the command that adds it when the project does not have it. An entry from the official list lists the newest release this CLI knows as latest and the project's Core version; its add command pins the project's Core version, else the Core range it declares (quoted), else the latest release. A version or item the official list does not show answers ERR_UNKNOWN_PACKAGE.",+ "One package: its package (the npm package the result is about), what the shown version adds, whether the project has it, its versions and latest release when a source knows them, and the command that adds it when the project does not have it. An entry from the official list lists the newest release this CLI knows as latest and the project's Core version; its add command pins the project's Core version, else the Core range it declares (quoted), else the latest release. A version or item the official list does not show answers ERR_UNKNOWN_PACKAGE.",},{type: 'discover.detail.doc',description:- 'The validated ComponentDoc for one installed component, for an @scope/name/Component query.',+ 'The validated ComponentDoc for one installed component, for an @scope/name/Component query, plus package, the npm package that owns the component.',},{type: 'discover.item',description:- 'One item that is not an installed component: its kind, name, the package and version that add it, and whether the project has the package.',+ 'One item that is not an installed component: its kind, name, the package and version that add it, and whether the project has the package. The envelope\'s package names the same package.',},{type: 'discover.search',diff --git a/packages/cli/api/discover/discover.type.mjs b/packages/cli/api/discover/discover.type.mjsindex 10af39a354..39d38354fe 100644--- a/packages/cli/api/discover/discover.type.mjs+++ b/packages/cli/api/discover/discover.type.mjs@@ -44,6 +44,7 @@* An installed integration, or an official package the project declares.* @typedef {object} DiscoverListEntry* @property {string} name+ * @property {string} package The npm package — always equal to `name`.* @property {string} category* @property {string[]} components* @property {string} [version]@@ -61,6 +62,7 @@* A package the project could add.* @typedef {object} DiscoverAvailableEntry* @property {string} name+ * @property {string} package The npm package — always equal to `name`.* @property {string} [version] Its latest release.* @property {string[]} components* @property {string[]} [templates]@@ -95,6 +97,7 @@* astryx --json discover @scope/name[@version]* @typedef {object} DiscoverDetailResponse* @property {'discover.detail'} type+ * @property {string} package The npm package this result is about.* @property {DiscoverListEntry & {* installed: boolean,* installedVersion?: string,@@ -115,6 +118,7 @@* astryx --json discover @scope/name/Component* @typedef {object} DiscoverDetailDocResponse* @property {'discover.detail.doc'} type+ * @property {string} package The npm package that owns the component.* @property {import('@astryxdesign/cli/authoring').ComponentDoc} data*/@@ -123,6 +127,7 @@* installed component.* @typedef {object} DiscoverItemResponse* @property {'discover.item'} type+ * @property {string} package The npm package that owns the item.* @property {{* package: string,* version?: string,diff --git a/packages/cli/api/discover/list/list.test.mjs b/packages/cli/api/discover/list/list.test.mjsindex 103f267c21..dbe31bd3d3 100644--- a/packages/cli/api/discover/list/list.test.mjs+++ b/packages/cli/api/discover/list/list.test.mjs@@ -32,6 +32,7 @@ describe('discover.list leaf', () => {expect(res.data).toEqual([{name: '@acme/widgets',+ package: '@acme/widgets',category: '@acme/widgets',components: ['Alpha', 'Beta'],version: '1.2.3',@@ -77,6 +78,7 @@ describe('discover.list leaf with discover sources', () => {expect(res.data).toEqual([{name: '@acme/widgets',+ package: '@acme/widgets',category: '@acme/widgets',components: ['Alpha'],version: '1.2.3',diff --git a/packages/cli/api/discover/search/search.mjs b/packages/cli/api/discover/search/search.mjsindex a9915df055..b467c2e970 100644--- a/packages/cli/api/discover/search/search.mjs+++ b/packages/cli/api/discover/search/search.mjs@@ -6,9 +6,12 @@** A free-text query always answers with a list, so its response type depends* on the form of the query and never on what the project has:- * 1. any matches -> discover.search- * 2. fuzzy hits (distance <= 3) -> throw ERR_NOT_FOUND with suggestions- * 3. otherwise -> throw ERR_NOT_FOUND+ * 1. any matches, a near-miss name included -> discover.search (a one- to+ * three-edit miss counts when both words are long enough: 5, 8 and 11+ * letters)+ * 2. other fuzzy hits (distance <= 3) -> throw ERR_NOT_FOUND with+ * suggestions+ * 3. otherwise -> throw ERR_NOT_FOUND* Matches are installed components, the project's other installed items,* packages, and every item a source lists for a package the project could add.* A caller opens one item by its package path, which ../detail answers.@@ -31,7 +34,8 @@ const KIND_ORDER = ['package', ...DISCOVER_KINDS];/*** How well an item matches: 0 exact name, 1 name prefix, 2 name substring,- * 3 title, summary, keyword, or description; null for no match.+ * 3 a near-miss name (3.0, 3.1, 3.2 for one, two or three edits), 4 title,+ * summary, keyword, or description; null for no match.* @param {SearchItem} item* @param {string} lower* @returns {number | null}@@ -41,6 +45,19 @@ function rank(item, lower) {if (name === lower) return 0;if (name.startsWith(lower)) return 1;if (name.includes(lower)) return 2;+ // A near-miss name ranks above a match in the title or text: how closely+ // the name matches decides first (AST-051 FR4).+ // Typo tolerance: same minimum-length guards as search (api/search/search.mjs).+ // A one-edit miss is a typo only on words long enough that one edit rarely+ // makes a different real word.+ const dist = levenshteinDistance(lower, name);+ if (dist >= 1 && dist <= 3) {+ /** @type {Record<number, number>} */+ const MIN_LENGTHS = {1: 5, 2: 8, 3: 11};+ if (Math.min(lower.length, name.length) >= MIN_LENGTHS[dist]) {+ return 3 + (dist - 1) / 10;+ }+ }const text = [item.title,item.summary,@@ -50,14 +67,16 @@ function rank(item, lower) {.filter(Boolean).join('\n').toLowerCase();- return text.includes(lower) ? 3 : null;+ if (text.includes(lower)) return 4;+ return null;}/*** Search all packages for `query` (a free-text term that never starts with* `@`). Resolves to a search response when anything matches, even a single- * item or an exact component name, or throws AstryxError (ERR_NOT_FOUND) —- * with fuzzy suggestions when any exist.+ * item, an exact component name or a near-miss name long enough to be a+ * typo, or throws AstryxError (ERR_NOT_FOUND) — with fuzzy suggestions when+ * any exist.** @param {ScannedPackage[]} packages installed packages* @param {string} querydiff --git a/packages/cli/api/discover/search/search.test.mjs b/packages/cli/api/discover/search/search.test.mjsindex 70249cdd60..8e90943df5 100644--- a/packages/cli/api/discover/search/search.test.mjs+++ b/packages/cli/api/discover/search/search.test.mjs@@ -142,6 +142,73 @@ describe('discover.search leaf — empty query (parity with api/search)', () =>});});+describe('discover.search leaf — typo tolerance (parity with api/search)', () => {+ it('a one-edit miss on a 5+ letter name returns results, not ERR_NOT_FOUND', async () => {+ // 'Alphe' is one substitution from 'Alpha' (distance 1, both >= 5 chars)+ const res = await search(packages, 'Alphe', {});+ expect(res.type).toBe('discover.search');+ expect(res.data.matches.map(m => m.component)).toContain('Alpha');+ });++ it("ranks a near-miss name above a match in another item's text", async () => {+ const items = [+ {+ package: '@acme/charts',+ kind: 'component',+ name: 'Scheduler',+ description: 'Lighter than a Calendr widget',+ installed: false,+ },+ {+ package: '@acme/charts',+ kind: 'component',+ name: 'Calendar',+ installed: false,+ },+ ];+ // 'Calendr' is one edit from the name 'Calendar' and appears word for+ // word only in Scheduler's description.+ const res = await search(packages, 'Calendr', {items});+ const names = res.data.matches.map(m => m.component);+ expect(names.indexOf('Calendar')).toBeGreaterThanOrEqual(0);+ expect(names.indexOf('Calendar')).toBeLessThan(names.indexOf('Scheduler'));+ });++ it('orders near misses by how many edits away they are', async () => {+ const items = [+ {package: '@acme/charts', kind: 'component', name: 'Paginaters', installed: false},+ {package: '@acme/charts', kind: 'component', name: 'Paginator', installed: false},+ ];+ const res = await search(packages, 'Paginatr', {items});+ const names = res.data.matches.map(m => m.component);+ expect(names.indexOf('Paginator')).toBeLessThan(names.indexOf('Paginaters'));+ });++ it('a one-edit miss on a longer name returns results', async () => {+ // 'AlpheCard' vs 'AlphaCard' is distance 1, well above 5 chars+ const res = await search(packages, 'AlpheCard', {});+ expect(res.type).toBe('discover.search');+ expect(res.data.matches.map(m => m.component)).toContain('AlphaCard');+ });++ it('a short word with distance 1 still throws (below min-length guard)', async () => {+ // 'Betz' vs 'Beta' is distance 1, but both are only 4 chars (< 5)+ await expect(search(packages, 'Betz', {})).rejects.toMatchObject({+ code: 'ERR_NOT_FOUND',+ });+ });++ it('includes catalog items in fuzzy matches too', async () => {+ const items = [+ {package: '@acme/charts', kind: 'component', name: 'Alphabets', installed: false},+ ];+ // 'Alphabel' vs 'Alphabets' is distance 2, both >= 8 chars+ const res = await search(packages, 'Alphabel', {items});+ expect(res.type).toBe('discover.search');+ expect(res.data.matches.map(m => m.component)).toContain('Alphabets');+ });+});+describe('discover.search leaf across every kind and source', () => {/** @type {any[]} */const items = [diff --git a/packages/cli/clients/cli/commands/discover.mjs b/packages/cli/clients/cli/commands/discover.mjsindex f3871d862d..c53c9606cb 100644--- a/packages/cli/clients/cli/commands/discover.mjs+++ b/packages/cli/clients/cli/commands/discover.mjs@@ -488,7 +488,7 @@ export function registerDiscover(program) {: detail === 'compact'? formatCompact(docs, docs.name, ''): formatFull(docs);- emit(code(md));+ emit(record({package: result.package}), code(md));break;}diff --git a/packages/cli/clients/cli/commands/discover.sources.test.mjs b/packages/cli/clients/cli/commands/discover.sources.test.mjsindex 62dab145b1..a9b40d4012 100644--- a/packages/cli/clients/cli/commands/discover.sources.test.mjs+++ b/packages/cli/clients/cli/commands/discover.sources.test.mjs@@ -154,6 +154,7 @@ describe('astryx discover with a discover source', () => {expect(meta.available.slice(official.length)).toEqual([{name: '@test/charts',+ package: '@test/charts',components: ['Chart'],version: '2.0.0',templates: ['pages/Report'],@@ -162,6 +163,7 @@ describe('astryx discover with a discover source', () => {},{name: '@test/boards',+ package: '@test/boards',components: [],version: '1.0.0',templates: ['pages/DialBoard'],@@ -269,6 +271,10 @@ describe('astryx discover with a discover source', () => {cwd: project,});expect(JSON.parse(opened.stdout).type).toBe('discover.detail.doc');++ // Text mode names the package on stdout, so a pipe keeps it.+ const text = await runCli(['discover', '@test/kit/Dial'], {cwd: project});+ expect(text.stdout).toMatch(/package: @test\/kit/);});it('saves the answer in the user cache and writes nothing into the project', async () => {diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjsindex 35734c6671..d51269ff14 100644--- a/packages/cli/foundation/response/response-types.doc.mjs+++ b/packages/cli/foundation/response/response-types.doc.mjs@@ -117,22 +117,22 @@ export const doc = {{value: 'discover.list',description:- '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".',+ 'What the project has, the integrations it loads and the official packages it declares, official packages first (package, the npm package and always equal to name; 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 its package and 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".',},{value: 'discover.detail',description:- '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.',+ 'One package, for an @scope/name or @scope/name@version query: its package (the npm package the result is about), 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.',},{value: 'discover.detail.doc',description:- 'The validated ComponentDoc for one installed component, for an @scope/name/Component query.',+ 'The validated ComponentDoc for one installed component, for an @scope/name/Component query, plus package, the npm package that owns the component.',},{value: 'discover.item',description:- '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.',+ '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. The envelope\'s package names the same package.',},{value: 'discover.search',diff --git a/packages/cli/test/global-local.test.mjs b/packages/cli/test/global-local.test.mjsindex 7fdef447a0..ba5f52bc4d 100644--- a/packages/cli/test/global-local.test.mjs+++ b/packages/cli/test/global-local.test.mjs@@ -1656,6 +1656,7 @@ describe.skipIf(!POSIX)(expect(notOfficial(discover)).toEqual([{name: '@acme/widgets',+ package: '@acme/widgets',components: [],version: '1.0.0',source: 'installed for this computer',@@ -1695,6 +1696,7 @@ describe.skipIf(!POSIX)(expect(notOfficial(discover)).toEqual([{name: '@acme/widgets',+ package: '@acme/widgets',components: [],version: '1.0.0',source: 'installed for this computer',@@ -2046,6 +2048,7 @@ describe.skipIf(!POSIX)(expect(notOfficial(discover)).toEqual([{name: '@acme/widgets',+ package: '@acme/widgets',components: [],version: '1.0.0',source: 'installed for this computer',diff --git a/packages/cli/test/inv28-discover-provenance.test.mjs b/packages/cli/test/inv28-discover-provenance.test.mjsnew file mode 100644index 0000000000..284538e96d--- /dev/null+++ b/packages/cli/test/inv28-discover-provenance.test.mjs@@ -0,0 +1,112 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file INV28 provenance test for discover responses. In its own file because+ * the Project.load mock that discover needs would interfere with the theme+ * tests in inv28-package-provenance.test.mjs, which use the real Project.load+ * through runCli.+ */++import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';++const ACME = '@acme/widgets';++const projectLoadMock = vi.fn();+vi.mock('../foundation/config/project.mjs', async importOriginal => ({+ ...(await importOriginal()),+ Project: {load: (/** @type {unknown[]} */ ...args) => projectLoadMock(...args)},+}));+const {discover} = await import('../api/discover/discover.mjs');++vi.setConfig({testTimeout: 60_000, hookTimeout: 60_000});++describe('INV28: discover names the package', () => {+ /** @type {string} */+ let tmp;++ beforeEach(() => {+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-inv28-disc-'));+ const intDir = path.join(tmp, 'node_modules', '@acme', 'widgets');+ const compDir = path.join(intDir, 'components');+ fs.mkdirSync(compDir, {recursive: true});+ fs.writeFileSync(+ path.join(tmp, 'package.json'),+ JSON.stringify({name: 'proj', version: '1.0.0'}),+ );+ fs.writeFileSync(+ path.join(tmp, 'astryx.config.mjs'),+ `export default {integrations: ['@acme/widgets']};\n`,+ );+ fs.writeFileSync(+ path.join(intDir, 'package.json'),+ JSON.stringify({name: ACME, version: '2.0.0'}),+ );+ fs.writeFileSync(+ path.join(intDir, 'astryx.integration.mjs'),+ `export default {components: './components'};\n`,+ );+ fs.writeFileSync(+ path.join(compDir, 'Widget.doc.mjs'),+ "export default {\n type: 'component',\n name: 'Widget',\n" ++ " usage: {description: 'A widget.'},\n" ++ " props: [{name: 'size', type: 'number', description: 'Size.'}],\n};\n",+ );+ fs.writeFileSync(+ path.join(compDir, 'Widget.tsx'),+ 'export function Widget() { return null; }\n',+ );+ projectLoadMock.mockReset();+ projectLoadMock.mockResolvedValue({+ cwd: tmp,+ integrations: [ACME],+ loadedIntegrations: [+ {+ name: ACME,+ version: '2.0.0',+ components: compDir,+ templates: undefined,+ codemods: undefined,+ __packageDir: intDir,+ },+ ],+ });+ });++ afterEach(() => {+ fs.rmSync(tmp, {recursive: true, force: true});+ });++ it('discover.list entries each carry package', async () => {+ const res = /** @type {any} */ (await discover());+ expect(res.type).toBe('discover.list');+ expect(res.package).toBeUndefined();+ expect(res.data.length).toBeGreaterThan(0);+ for (const entry of res.data) {+ expect(entry.package, entry.name).toBe(entry.name);+ }+ });++ it('discover.detail names the package in the envelope', async () => {+ const res = /** @type {any} */ (await discover(ACME));+ expect(res.type).toBe('discover.detail');+ expect(res.package).toBe(ACME);+ });++ it('discover.detail.doc names the package in the envelope', async () => {+ const res = /** @type {any} */ (await discover(`${ACME}/Widget`));+ expect(res.type).toBe('discover.detail.doc');+ expect(res.package).toBe(ACME);+ });++ it('discover.search matches each carry package', async () => {+ const res = /** @type {any} */ (await discover('Widget'));+ expect(res.type).toBe('discover.search');+ expect(res.package).toBeUndefined();+ for (const m of res.data.matches) {+ expect(m.package, m.component).toEqual(expect.any(String));+ }+ });+});