An open source design system that's fully customizable and agent ready
TypeScript
feat(cli): discover lists the official Astryx packages first, from a list built into each release (#7495)
Joey9e97808d9cec
diff --git a/.changeset/discover-official-packages.md b/.changeset/discover-official-packages.mdnew file mode 100644index 0000000000..b5161225ee--- /dev/null+++ b/.changeset/discover-official-packages.md@@ -0,0 +1,6 @@+---+'@astryxdesign/cli': patch+---++[feat] `astryx discover` lists the official Astryx packages, first, from a list each CLI release carries, so a project with no discover source sees the official themes, even offline. Each entry in `meta.available` carries the command that adds it (`install`), so a project that loads no integration and has no discover source of its own, where every query still answers with the list, can add a package straight from it. An official entry's `latest` is the newest release the CLI knows (its own version on a release CLI, or a newer Core release the project has), and its `versions` also list the project's Core version, so both can be looked up. Its add command pins the project's Core version (installed, or declared exactly), else the Core range the project declares (quoted), else the latest release; on a canary CLI with no Core it pins none for packages released with Core, and canary-only packages are listed only beside a canary Core or no Core. Official entries name `Astryx` as their `source`, and `meta.sources` reports the list last. A project's or an integration's source keeps its entry for an official package, and for any package of the same integration. A theme package that the project's own package.json declares as a dependency, under an npm alias too, shows as installed from any folder of the project, and a theme's add text ends with `astryx theme add <slug>`. A version or item that the official list does not show still answers `ERR_UNKNOWN_PACKAGE`, as before.+@josephfarinadiff --git a/package.json b/package.jsonindex 890c0e65e9..bc33b9c75e 100644--- a/package.json+++ b/package.json@@ -4,8 +4,9 @@"private": true,"license": "MIT","scripts": {- "build": "pnpm -F @astryxdesign/build build && pnpm -F @astryxdesign/core build && pnpm -F @astryxdesign/lab build && pnpm -F @astryxdesign/charts build && pnpm -F @astryxdesign/richtext build && pnpm -F @astryxdesign/vega build && pnpm -F @astryxdesign/theme-neutral build && pnpm -F @astryxdesign/theme-matcha build && pnpm -F @astryxdesign/theme-stone build && pnpm -F @astryxdesign/theme-gothic build && pnpm -F @astryxdesign/theme-chocolate build && pnpm -F @astryxdesign/theme-y2k build && pnpm -F @astryxdesign/theme-butter build && pnpm -F @astryxdesign/theme-probe build && pnpm bundle:cli-themes && pnpm -F @astryxdesign/cli sync:api-types",+ "build": "pnpm -F @astryxdesign/build build && pnpm -F @astryxdesign/core build && pnpm -F @astryxdesign/lab build && pnpm -F @astryxdesign/charts build && pnpm -F @astryxdesign/richtext build && pnpm -F @astryxdesign/vega build && pnpm -F @astryxdesign/theme-neutral build && pnpm -F @astryxdesign/theme-matcha build && pnpm -F @astryxdesign/theme-stone build && pnpm -F @astryxdesign/theme-gothic build && pnpm -F @astryxdesign/theme-chocolate build && pnpm -F @astryxdesign/theme-y2k build && pnpm -F @astryxdesign/theme-butter build && pnpm -F @astryxdesign/theme-probe build && pnpm bundle:cli-themes && pnpm bundle:cli-official-packages && pnpm -F @astryxdesign/cli sync:api-types","bundle:cli-themes": "node scripts/generate-cli-themes.mjs",+ "bundle:cli-official-packages": "node scripts/generate-cli-official-packages.mjs","generate:neutral-palette-refs": "node scripts/generate-neutral-palette-refs.mjs","check:neutral-palette-refs": "node scripts/generate-neutral-palette-refs.mjs --check","dev": "pnpm -F @astryxdesign/storybook dev",diff --git a/packages/cli/README.md b/packages/cli/README.mdindex 4e0d665427..2ce02d55a4 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -437,7 +437,7 @@ 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` | The integrations the project loads (name, category, components, version, a list per other kind they add, and latest when a source knows it); with a discover source, meta.available lists what the project could add and meta.sources reports each source; when empty it carries meta.configured to tell "nothing configured" from "nothing discovered". |+| `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. |diff --git a/packages/cli/api/discover/_adapter.mjs b/packages/cli/api/discover/_adapter.mjsindex e1c830e917..6c2a184c1c 100644--- a/packages/cli/api/discover/_adapter.mjs+++ b/packages/cli/api/discover/_adapter.mjs@@ -8,6 +8,7 @@* none of them touch the integration system, the filesystem, or a source. This* adapter does: it resolves the project's installed integrations and what each* one adds, calls every discover source and keeps a saved copy of each answer,+ * reads the official list the CLI carries after them,* locates and loads a component's doc, and names the package manager's add* command. Keeping that I/O here (INV21) is what lets `list`, `detail`,* `detail/doc`, `detail/item`, and `search` stay pure projections.@@ -28,13 +29,29 @@ import {import {loadDocs} from '../../foundation/discovery/component-loader.mjs';import {collectIdentities} from '../../foundation/integrations/contribution-inventory.mjs';import {detectPackageManager} from '../../foundation/env/package-manager.mjs';+import {isValidSemver, semverCompare} from '../../foundation/env/semver.mjs';import {assertWithin} from '../../foundation/fs/path-safety.mjs';+import {CLI_ROOT, findInstalledPackage} from '../../foundation/fs/paths.mjs';import {parseDiscoverCatalog} from '../../authoring/discover/parse.mjs';import {AstryxError} from '../error.mjs';import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';const SOURCE_TIMEOUT_MS = 30_000;+/** The name the official list goes by, as a source and on each of its entries. */+export const OFFICIAL_SOURCE_NAME = 'Astryx';++/** Where the official list comes from: the CLI package that carries it. */+const OFFICIAL_SOURCE_FROM = '@astryxdesign/cli';++/** The official list, generated from the repository when the CLI is built. */+export const OFFICIAL_LIST_FILE = path.join(+ CLI_ROOT,+ 'assets',+ 'discover',+ 'official-packages.json',+);+const DEPENDENCY_FIELDS = ['dependencies','devDependencies',@@ -48,6 +65,29 @@ const DEPENDENCY_FIELDS = [* @typedef {import('../../authoring/discover/type').DiscoverSource} DiscoverSource*/+/**+ * An official package as this CLI lists it (spec:AST-051 FR11), with what its+ * add command pins (FR2): the project's Core version, the Core range the+ * project declares, or the latest release; with none, it pins nothing.+ * @typedef {DiscoverPackage & {pin?: string}} OfficialPackage+ */++/**+ * The official packages the project's package.json declares: the real package+ * name of each, mapped to the name it is installed under (an npm alias such as+ * `"my-theme": "npm:@astryxdesign/[email protected]"` installs under+ * `my-theme`). `dependency` holds those declared in dependencies,+ * devDependencies or optionalDependencies, which make a package the project's+ * own; `any` adds peerDependencies, which only keep it from being offered.+ * @typedef {{dependency: Map<string, string>, any: Set<string>}} OfficialDeclarations+ */++/**+ * The official list as this CLI reads it. `error` says why the file could not+ * be read; the list is then empty and discover reports it like a failed source.+ * @typedef {{packages: OfficialPackage[], error?: string}} OfficialList+ */+/*** An installed integration with what it adds, per kind. `components` is the* scanned component list the discover leaves have always used.@@ -64,7 +104,8 @@ const DEPENDENCY_FIELDS = [* @typedef {object} SourceState* @property {string} name the source's own name, or where it came from when it* gave none- * @property {string} from `astryx.config`, or the integration that exports it+ * @property {string} from `astryx.config`, the integration that exports it, or+ * `@astryxdesign/cli` for the official list* @property {'fresh' | 'saved' | 'failed'} status* @property {string} [generatedAt]* @property {boolean} [complete]@@ -73,9 +114,10 @@ const DEPENDENCY_FIELDS = [*//**- * Everything every source returned, merged. When two sources list the same- * package, the earlier source's entry is kept.- * @typedef {{sources: SourceState[], packages: Array<DiscoverPackage & {source: string}>}} CatalogResult+ * Everything every source returned, merged, the official list last. When two+ * sources list the same package, the earlier source's entry is kept. `official`+ * marks an entry the official list supplied.+ * @typedef {{sources: SourceState[], packages: Array<DiscoverPackage & {source: string, official?: true}>}} CatalogResult*//**@@ -225,13 +267,151 @@ export function declaredDependencies(project) {return names;}+/**+ * The nearest package.json at or above the project's folder, read. Discover+ * runs from any folder of a project; this is the project's own manifest.+ * @param {Project | undefined} project+ * @returns {{dir: string, pkg: Record<string, any>} | null}+ */+function nearestManifest(project) {+ let dir = project?.cwd ?? process.cwd();+ for (;;) {+ const file = path.join(dir, 'package.json');+ if (fs.existsSync(file)) {+ try {+ return {dir, pkg: JSON.parse(fs.readFileSync(file, 'utf8'))};+ } catch {+ return null;+ }+ }+ const parent = path.dirname(dir);+ if (parent === dir) return null;+ dir = parent;+ }+}++/** The fields that make a declared package the project's own. */+const OWN_DEPENDENCY_FIELDS = [+ 'dependencies',+ 'devDependencies',+ 'optionalDependencies',+];++/**+ * The package a dependency entry installs: its own name, or the target of an+ * npm alias (`npm:<name>@<range>`).+ * @param {string} name+ * @param {unknown} spec+ * @returns {string}+ */+function declaredPackage(name, spec) {+ if (typeof spec !== 'string' || !spec.startsWith('npm:')) return name;+ const target = spec.slice('npm:'.length);+ const at = target.indexOf('@', 1);+ return at > 0 ? target.slice(0, at) : target;+}++/**+ * What the project's own package.json, the nearest one above the folder+ * discover runs in, declares among the official packages.+ * @param {Project | undefined} project+ * @param {OfficialPackage[]} official+ * @returns {OfficialDeclarations}+ */+export function officialDeclarations(project, official) {+ const names = new Set(official.map(pkg => pkg.package));+ /** @type {OfficialDeclarations} */+ const declared = {dependency: new Map(), any: new Set()};+ const manifest = nearestManifest(project);+ if (manifest == null) return declared;+ for (const field of DEPENDENCY_FIELDS) {+ for (const [local, spec] of Object.entries(manifest.pkg?.[field] ?? {})) {+ const real = declaredPackage(local, spec);+ if (!names.has(real)) continue;+ declared.any.add(real);+ if (+ OWN_DEPENDENCY_FIELDS.includes(field) &&+ !declared.dependency.has(real)+ )+ declared.dependency.set(real, local);+ }+ }+ return declared;+}++/**+ * One part of a semver range: an optional comparator and a version that may+ * use `x` or `*` wildcards.+ */+const RANGE_PART =+ /^(?:[<>]=?|=|\^|~)?v?(?:\d+|[xX*])(?:\.(?:\d+|[xX*])){0,2}(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u;++/**+ * Whether a dependency spec is a semver range every supported package manager+ * resolves: comparators, wildcards, `||` and hyphen ranges. A dist-tag, path,+ * URL, alias or workspace protocol is not.+ * @param {string} spec+ * @returns {boolean}+ */+function isSemverRange(spec) {+ const parts = spec+ .trim()+ .split(/\s*\|\|\s*|\s+/u)+ .filter(part => part !== '-');+ return parts.length > 0 && parts.every(part => RANGE_PART.test(part));+}++/**+ * The project's Core: the installed copy's version, else what its own+ * package.json declares (a fresh clone before install): an exact `version`, or+ * a semver `range`. Neither, for a declaration no package manager can pin+ * against, such as a path or a dist-tag. Null when the project has no Core.+ * @param {Project | undefined} project+ * @returns {{version?: string, range?: string} | null}+ */+function projectCore(project) {+ const installed = installedVersion(project, '@astryxdesign/core');+ if (installed) return {version: installed};+ const manifest = nearestManifest(project);+ for (const field of OWN_DEPENDENCY_FIELDS) {+ const spec = manifest?.pkg?.[field]?.['@astryxdesign/core'];+ if (typeof spec !== 'string') continue;+ // A space after an operator (`~ 0.6.8`, `>= 0.6.8 < 0.7.0`) is allowed by+ // node-semver; join each operator to its version before reading the spec.+ const range = spec.trim().replace(/([<>]=?|=|\^|~)\s+/gu, '$1');+ const exact = range.replace(/^=/u, '');+ if (isValidSemver(exact)) return {version: exact};+ return isSemverRange(range) ? {range} : {};+ }+ return null;+}++/**+ * Newest first: by release number, then a release before its prereleases.+ * @param {string} a+ * @param {string} b+ * @returns {number}+ */+function newerFirst(a, b) {+ const byNumber = semverCompare(b, a);+ if (byNumber !== 0) return byNumber;+ const aRelease = !a.includes('-');+ if (aRelease !== !b.includes('-')) return aRelease ? -1 : 1;+ return b.localeCompare(a, 'en', {numeric: true});+}+/*** The command that adds a package with the project's package manager. Discover- * only prints it; it never runs it.+ * only prints it; it never runs it. Asked for one version, it adds that+ * version. Given the official list, it otherwise pins an official package to+ * what its entry names (spec:AST-051 FR2): the project's Core version or+ * declared Core range, else the latest release. A range is quoted, because+ * `^`, `<`, `>`, `|` and spaces mean something to a shell.* @param {Project | undefined} project+ * @param {{official?: OfficialPackage[]}} [options]* @returns {(name: string, version?: string) => string}*/-export function addCommand(project) {+export function addCommand(project, {official = []} = {}) {const pm = detectPackageManager(project?.cwd ?? process.cwd());const verb =pm === 'pnpm'@@ -241,7 +421,15 @@ export function addCommand(project) {: pm === 'bun'? 'bun add': 'npm install';- return (name, version) => `${verb} ${version ? `${name}@${version}` : name}`;+ const byName = new Map(official.map(pkg => [pkg.package, pkg]));+ return (name, version) => {+ if (version) return `${verb} ${name}@${version}`;+ const pin = byName.get(name)?.pin;+ if (!pin) return `${verb} ${name}`;+ return isValidSemver(pin)+ ? `${verb} ${name}@${pin}`+ : `${verb} "${name}@${pin}"`;+ };}/**@@ -347,8 +535,8 @@ async function callSource(source, request, label, timeoutMs) {}/**- * Call every discover source — the project's `discover` first, then each- * integration's in load order — once per distinct function. A source that+ * Call the project's own discover sources — the project's `discover` first,+ * then each integration's in load order — once per distinct function. A source that* throws, times out, or returns an invalid catalog falls back to its saved copy;* with none, it is reported and adds nothing. The others always count.*@@ -358,7 +546,7 @@ async function callSource(source, request, label, timeoutMs) {* @param {{cacheDir?: string, timeoutMs?: number}} [options]* @returns {Promise<CatalogResult>}*/-export async function callSources(project, request = {}, options = {}) {+async function callOwnSources(project, request = {}, options = {}) {const {cacheDir = defaultCacheDir(), timeoutMs = SOURCE_TIMEOUT_MS} = options;/** @type {CatalogResult} */const result = {sources: [], packages: []};@@ -433,6 +621,257 @@ export async function callSources(project, request = {}, options = {}) {return result;}+/**+ * Call every discover source (see {@link callOwnSources}), then read the+ * official list (spec:AST-051 FR11). The list comes last, so a source keeps+ * its entry for an official package, or for any package of the same+ * integration (FR7); the list adds the official packages no source covers.+ * The result stays in source order; discover puts official packages first+ * only where it shows them ({@link officialFirst}).+ *+ * @param {Project | undefined} project+ * @param {{package?: string, version?: string}} [request]+ * @param {{cacheDir?: string, timeoutMs?: number, official?: OfficialList}} [options]+ * `official`: the list {@link officialList} read; read here when absent+ * @returns {Promise<CatalogResult>}+ */+export async function callSources(project, request = {}, options = {}) {+ const {official = officialList({project}), ...rest} = options;+ const own = await callOwnSources(project, request, rest);+ // A source's entry wins for its package and for the integration it+ // publishes under any name (FR7), so a fork or mirror keeps its place.+ const seen = new Set(+ own.packages.flatMap(pkg => [pkg.package, pkg.integration, ...pkg.aliases]),+ );+ /** @type {CatalogResult['packages']} */+ const added = [];+ for (const {pin: _pin, ...pkg} of official.packages) {+ if (seen.has(pkg.package)) continue;+ if (request.package && pkg.package !== request.package) continue;+ added.push({...pkg, source: OFFICIAL_SOURCE_NAME, official: true});+ }+ return {+ sources: [+ ...own.sources,+ official.error+ ? {+ name: OFFICIAL_SOURCE_NAME,+ from: OFFICIAL_SOURCE_FROM,+ status: 'failed',+ error: official.error,+ }+ : {+ name: OFFICIAL_SOURCE_NAME,+ from: OFFICIAL_SOURCE_FROM,+ status: 'fresh',+ complete: true,+ },+ ],+ // Source order: the first entry per integration is the one discover+ // keeps. Official packages are put first only where discover shows them.+ packages: [...own.packages, ...added],+ };+}++/**+ * Official packages first, in the official list's order; the rest keep theirs.+ * @template T+ * @param {T[]} items+ * @param {OfficialPackage[]} official+ * @param {(item: T) => string} nameOf+ * @returns {T[]}+ */+export function officialFirst(items, official, nameOf) {+ const order = new Map(official.map((pkg, index) => [pkg.package, index]));+ const rank = (/** @type {T} */ item) => order.get(nameOf(item)) ?? order.size;+ return [...items].sort((a, b) => rank(a) - rank(b));+}++/**+ * The official list this CLI carries (spec:AST-051 FR11). The file holds no+ * versions; each entry takes them from this CLI and the project:+ *+ * - Its latest release is the newest release this CLI knows: its own version+ * on a release CLI, or the project's Core version when that is a newer+ * release.+ * - A package released with Core lists a release CLI's own version and the+ * project's Core version (installed, else declared exactly), so each,+ * the latest release included, can be looked up. Its add command pins the project's Core version, else the Core range+ * the project declares, else the latest release; nothing on a canary CLI in+ * a project with no Core, which may have been published without it.+ * - A canary-only package is listed only by a canary CLI, as a prerelease at+ * the project's Core version when that is a prerelease, else at the CLI's+ * own version when the project has no Core. It is not listed beside a+ * released or declared Core, which it cannot be installed with.+ *+ * @param {{file?: string, version?: string, project?: Project}} [options] the+ * list file and the CLI version to read it for, both defaulting to this+ * CLI's own, and the project whose Core decides the versions+ * @returns {OfficialList}+ */+export function officialList({+ file = OFFICIAL_LIST_FILE,+ version,+ project,+} = {}) {+ try {+ const cli = version ?? packageVersion(CLI_ROOT);+ if (cli == null) throw new Error('the CLI package names no version');+ const core = project == null ? null : projectCore(project);+ const list = JSON.parse(fs.readFileSync(file, 'utf8'));+ const canaryCli = /-canary\./u.test(cli);+ /** @type {(v: string | undefined) => v is string} */+ const isRelease = v => v != null && !v.includes('-');+ const latest =+ [cli, core?.version].filter(isRelease).sort(newerFirst)[0] ?? null;+ /** @type {OfficialPackage[]} */+ const packages = [];+ for (const pkg of list.packages) {+ /** @type {string[]} */+ let listed = [];+ /** @type {string | null} */+ let entryLatest = null;+ /** @type {string | undefined} */+ let pin;+ if (pkg.canaryOnly === true) {+ if (!canaryCli) continue;+ if (core == null) pin = cli;+ else if (core.version && !isRelease(core.version)) pin = core.version;+ else continue;+ listed = [pin];+ } else if (pkg.releasedWithCore === true) {+ entryLatest = latest;+ listed = [+ ...new Set(+ [isRelease(cli) ? cli : undefined, core?.version].filter(+ /** @returns {v is string} */ v => v != null,+ ),+ ),+ ].sort(newerFirst);+ // The project's Core version, else the plain range it declares, else+ // the latest release (spec:AST-051 FR11): a Core declared as+ // `workspace:*`, a `file:` path or a dist-tag, and not installed,+ // still gets a pin.+ pin =+ core == null+ ? canaryCli+ ? undefined+ : cli+ : (core.version ?? core.range ?? entryLatest ?? undefined);+ }+ packages.push({+ package: pkg.package,+ integration: pkg.package,+ aliases: [],+ ...(pkg.description ? {description: pkg.description} : {}),+ latest: entryLatest,+ versions: listed.map(v => ({+ version: v,+ publishedAt: null,+ prerelease: v.includes('-'),+ status: 'ok',+ })),+ contributions: pkg.contributions,+ ...(pin ? {pin} : {}),+ });+ }+ return {packages};+ } catch (err) {+ return {+ packages: [],+ error: `the official list could not be read (${err instanceof Error ? err.message : String(err)})`,+ };+ }+}++/**+ * What the project has: its installed integrations plus each official package+ * its own package.json declares as a dependency whose entry the official list+ * supplied, official packages first. A declared official package that a source+ * lists stays as that source shows it (FR7). One that failed to load as an+ * integration stays out. A declared one takes what it adds from the list and+ * its version from the copy the project installed, under an npm alias too.+ *+ * @param {Project | undefined} project+ * @param {InstalledPackage[]} installed from {@link describeInstalled}+ * @param {CatalogResult} catalog+ * @param {OfficialDeclarations} declared from {@link officialDeclarations}+ * @param {OfficialPackage[]} official the official list, for the order+ * @returns {Array<InstalledPackage & {declaredOfficial?: true}>}+ */+export function withDeclaredOfficial(+ project,+ installed,+ catalog,+ declared,+ official,+) {+ const loaded = new Set(project?.loadedIntegrations.map(i => i.name) ?? []);+ /** @type {Array<InstalledPackage & {declaredOfficial?: true}>} */+ const added = [];+ for (const pkg of catalog.packages) {+ const local = declared.dependency.get(pkg.package);+ if (!pkg.official || local == null || loaded.has(pkg.package)) continue;+ const version = installedVersion(project, local);+ added.push(+ /** @type {InstalledPackage & {declaredOfficial: true}} */ (+ /** @type {unknown} */ ({+ name: pkg.package,+ category: pkg.package,+ ...(version ? {version} : {}),+ ...(pkg.description ? {description: pkg.description} : {}),+ ...itemLists(pkg.contributions),+ declaredOfficial: true,+ })+ ),+ );+ }+ return officialFirst([...installed, ...added], official, pkg => pkg.name);+}++/**+ * Group contributions into the entry fields, one list per kind that has any.+ * `components` is always present, like on a scanned package.+ * @param {DiscoverPackage['contributions']} contributions+ * @returns {Record<string, string[]>}+ */+function itemLists(contributions) {+ /** @type {Record<string, string[]>} */+ const lists = {components: []};+ for (const [kind, field] of KIND_FIELDS) {+ const names = contributions.filter(c => c.kind === kind).map(c => c.name);+ if (names.length > 0) lists[field] = names;+ }+ return lists;+}++/**+ * The version in a package directory's package.json, if it names one.+ * @param {string} dir+ * @returns {string | undefined}+ */+function packageVersion(dir) {+ try {+ const {version} = JSON.parse(+ fs.readFileSync(path.join(dir, 'package.json'), 'utf8'),+ );+ return typeof version === 'string' && version ? version : undefined;+ } catch {+ return undefined;+ }+}++/**+ * The version of `name` the project installed, if it installed it.+ * @param {Project | undefined} project+ * @param {string} name+ * @returns {string | undefined}+ */+function installedVersion(project, name) {+ const dir = findInstalledPackage(project?.cwd ?? process.cwd(), name);+ return dir == null ? undefined : packageVersion(dir);+}+/** The list and detail entry fields for each item kind, in display order. */export const KIND_FIELDS = /** @type {const} */ ([['component', 'components'],diff --git a/packages/cli/api/discover/_adapter.test.mjs b/packages/cli/api/discover/_adapter.test.mjsindex 44f7b0cd05..fe927a7400 100644--- a/packages/cli/api/discover/_adapter.test.mjs+++ b/packages/cli/api/discover/_adapter.test.mjs@@ -1,16 +1,32 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file Tests for how the discover adapter calls discover sources: order,- * failure isolation, timeouts, and the saved copy. Sources are plain functions- * on a stand-in project, and the saved copies go to a temp directory.+ * @file Tests for how the discover adapter reads the official list and calls+ * discover sources: order, failure isolation, timeouts, and the saved copy,+ * plus what the official list adds to the installed list and the add command.+ * Sources are plain functions on a stand-in project, and the saved copies go+ * to a temp directory.*/import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';-import {callSources} from './_adapter.mjs';+import {+ addCommand,+ callSources,+ OFFICIAL_LIST_FILE,+ officialDeclarations,+ officialList,+ withDeclaredOfficial,+} from './_adapter.mjs';+import {parseDiscoverCatalog} from '../../authoring/discover/parse.mjs';++/** No official packages, so a test sees only its own sources after it. */+const NO_OFFICIAL = {packages: []};++/** How the official list reports itself among the sources. */+const OFFICIAL_STATE = ['Astryx', '@astryxdesign/cli', 'fresh'];/*** @param {string} name@@ -43,11 +59,28 @@ function pkg(name, extra = {}) {}/**- * @param {{config?: object, integrations?: object[]}} parts+ * @param {{config?: object, integrations?: object[], cwd?: string}} parts* @returns {any}*/-function project({config = {}, integrations = []}) {- return {config, loadedIntegrations: integrations, cwd: '/virtual/project'};+function project({config = {}, integrations = [], cwd = '/virtual/project'}) {+ return {config, loadedIntegrations: integrations, cwd};+}++/**+ * An official package as officialList() returns it.+ * @param {string} name+ * @param {object} [extra]+ */+function official(name, extra = {}) {+ return {+ ...pkg(name, {latest: '0.7.1'}),+ versions: [+ {version: '0.7.1', publishedAt: null, prerelease: false, status: 'ok'},+ ],+ contributions: [{kind: 'theme', name: name.split('-').pop()}],+ pin: '0.7.1',+ ...extra,+ };}let cacheDir;@@ -82,13 +115,14 @@ describe('callSources', () => {],}),{},- {cacheDir},+ {cacheDir, official: NO_OFFICIAL},);expect(calls).toEqual(['own', 'shared']);expect(result.sources.map(s => [s.name, s.from, s.status])).toEqual([['Own', 'astryx.config', 'fresh'],['Shared', '@x/first', 'fresh'],+ OFFICIAL_STATE,]);expect(result.packages.map(p => [p.package, p.latest, p.source])).toEqual([['@a/one', '9.9.9', 'Own'],@@ -102,7 +136,7 @@ describe('callSources', () => {await callSources(project({integrations: [{name: '@x/src', __discover: source}]}),{package: '@a/one', version: '1.0.0'},- {cacheDir},+ {cacheDir, official: NO_OFFICIAL},);expect(source).toHaveBeenCalledWith({@@ -134,7 +168,7 @@ describe('callSources', () => {],}),{},- {cacheDir},+ {cacheDir, official: NO_OFFICIAL},);expect(result.sources.map(s => [s.from, s.status])).toEqual([@@ -142,6 +176,7 @@ describe('callSources', () => {['@x/bad', 'failed'],['@x/broken', 'failed'],['@x/good', 'fresh'],+ ['@astryxdesign/cli', 'fresh'],]);expect(result.sources[0].error).toContain('offline');expect(result.sources[1].error).toContain('schemaVersion 2');@@ -160,7 +195,7 @@ describe('callSources', () => {const result = await callSources(project({integrations: [{name: '@x/slow', __discover: slow}]}),{},- {cacheDir, timeoutMs: 20},+ {cacheDir, timeoutMs: 20, official: NO_OFFICIAL},);expect(result.sources[0]).toMatchObject({@@ -177,10 +212,11 @@ describe('callSources', () => {return catalog('S', [pkg('@a/one')]);};const p = project({integrations: [{name: '@x/src', __discover: source}]});+ const options = {cacheDir, official: NO_OFFICIAL};- await callSources(p, {}, {cacheDir});+ await callSources(p, {}, options);online = false;- const offline = await callSources(p, {}, {cacheDir});+ const offline = await callSources(p, {}, options);expect(offline.sources[0]).toMatchObject({name: 'S',@@ -190,7 +226,7 @@ describe('callSources', () => {});expect(offline.packages.map(x => x.package)).toEqual(['@a/one']);- const otherRequest = await callSources(p, {package: '@a/one'}, {cacheDir});+ const otherRequest = await callSources(p, {package: '@a/one'}, options);expect(otherRequest.sources[0].status).toBe('failed');});@@ -202,14 +238,560 @@ describe('callSources', () => {],}),{},- {cacheDir},+ {cacheDir, official: NO_OFFICIAL},);expect(fs.readdirSync(path.join(cacheDir, 'discover'))).toHaveLength(1);expect(fs.existsSync('/virtual/project')).toBe(false);});- it('returns nothing when there is no project', async () => {- expect(await callSources(undefined)).toEqual({sources: [], packages: []});+ it('returns only the official list when there is no project', async () => {+ const result = await callSources(+ undefined,+ {},+ {official: {packages: [official('@astryxdesign/theme-gothic')]}},+ );+ expect(result.sources.map(s => [s.name, s.from, s.status])).toEqual([+ OFFICIAL_STATE,+ ]);+ expect(result.packages.map(p => [p.package, p.source])).toEqual([+ ['@astryxdesign/theme-gothic', 'Astryx'],+ ]);+ });++ it('reads the official list last, so another source keeps its entry', async () => {+ const own = async () =>+ catalog('Own', [+ pkg('@a/two'),+ pkg('@astryxdesign/theme-matcha', {latest: '0.6.8'}),+ ]);+ const result = await callSources(+ project({config: {discover: own}}),+ {},+ {+ cacheDir,+ official: {+ packages: [+ official('@astryxdesign/theme-gothic'),+ official('@astryxdesign/theme-matcha'),+ ],+ },+ },+ );++ expect(result.sources.map(s => [s.name, s.from, s.status])).toEqual([+ ['Own', 'astryx.config', 'fresh'],+ OFFICIAL_STATE,+ ]);+ // The add command's pin stays with the list; a catalog entry never+ // carries it.+ for (const entry of result.packages)+ expect(entry).not.toHaveProperty('pin');+ // Source order: discover puts official packages first only where it+ // shows them.+ expect(+ result.packages.map(p => [p.package, p.latest, p.source, !!p.official]),+ ).toEqual([+ ['@a/two', '1.0.0', 'Own', false],+ ['@astryxdesign/theme-matcha', '0.6.8', 'Own', false],+ ['@astryxdesign/theme-gothic', '0.7.1', 'Astryx', true],+ ]);+ });++ it('keeps a source’s package for an official integration it publishes under another name', async () => {+ const own = async () =>+ catalog('Own', [+ pkg('@acme/gothic-fork', {+ integration: '@astryxdesign/theme-gothic',+ contributions: [{kind: 'theme', name: 'gothic'}],+ }),+ pkg('@acme/stone-mirror', {aliases: ['@astryxdesign/theme-stone']}),+ ]);+ const result = await callSources(+ project({config: {discover: own}}),+ {},+ {+ cacheDir,+ official: {+ packages: [+ official('@astryxdesign/theme-gothic'),+ official('@astryxdesign/theme-stone'),+ official('@astryxdesign/theme-matcha'),+ ],+ },+ },+ );+ expect(result.packages.map(p => [p.package, p.source])).toEqual([+ ['@acme/gothic-fork', 'Own'],+ ['@acme/stone-mirror', 'Own'],+ ['@astryxdesign/theme-matcha', 'Astryx'],+ ]);+ });++ it('answers a package request with only that official package', async () => {+ const result = await callSources(+ project({}),+ {package: '@astryxdesign/theme-matcha'},+ {+ cacheDir,+ official: {+ packages: [+ official('@astryxdesign/theme-gothic'),+ official('@astryxdesign/theme-matcha'),+ ],+ },+ },+ );+ expect(result.packages.map(p => p.package)).toEqual([+ '@astryxdesign/theme-matcha',+ ]);+ });++ it('reports an official list it could not read like a failed source', async () => {+ const result = await callSources(+ project({}),+ {},+ {cacheDir, official: {packages: [], error: 'the list is missing'}},+ );+ expect(result.sources.slice(-1)).toEqual([+ {+ name: 'Astryx',+ from: '@astryxdesign/cli',+ status: 'failed',+ error: 'the list is missing',+ },+ ]);+ expect(result.packages).toEqual([]);+ });+});++/**+ * A stand-in project folder whose installed Core is `version`.+ * @param {string} dir+ * @param {string} version+ */+function withCore(dir, version) {+ const at = path.join(dir, 'node_modules', '@astryxdesign', 'core');+ fs.mkdirSync(at, {recursive: true});+ fs.writeFileSync(+ path.join(at, 'package.json'),+ JSON.stringify({name: '@astryxdesign/core', version}),+ );+ return project({cwd: dir});+}++/** The version an entry lists, with its latest. */+const versionsOf = (+ /** @type {{latest: string | null, versions: {version: string, prerelease: boolean}[]} | undefined} */ entry,+) =>+ entry && {+ latest: entry.latest,+ versions: entry.versions.map(v => [v.version, v.prerelease]),+ };++/** @param {{package: string}[]} packages @param {string} name */+const find = (packages, name) => packages.find(p => p.package === name);++const NEUTRAL = '@astryxdesign/theme-neutral';++/** The canary-only package names in the committed list. */+function canaryOnlyNames() {+ return JSON.parse(fs.readFileSync(OFFICIAL_LIST_FILE, 'utf8'))+ .packages.filter((/** @type {{canaryOnly?: boolean}} */ p) => p.canaryOnly)+ .map((/** @type {{package: string}} */ p) => p.package);+}++describe('officialList', () => {+ it('gives every official package the release CLI’s version when the project has no Core', () => {+ const {packages, error} = officialList({version: '0.7.1'});+ expect(error).toBeUndefined();+ expect(packages.length).toBeGreaterThan(0);+ for (const entry of packages) {+ expect(entry.package.startsWith('@astryxdesign/')).toBe(true);+ expect(versionsOf(entry)).toEqual({+ latest: '0.7.1',+ versions: [['0.7.1', false]],+ });+ expect(entry.contributions.length).toBeGreaterThan(0);+ }+ expect(packages.map(p => p.package)).toContain(NEUTRAL);+ for (const name of canaryOnlyNames()) {+ expect(find(packages, name)).toBeUndefined();+ }+ });++ it('lists the latest release and the project’s Core version, and pins the Core version', () => {+ for (const [core, latest, versions] of [+ [+ '0.6.8',+ '0.7.1',+ [+ ['0.7.1', false],+ ['0.6.8', false],+ ],+ ],+ [+ '0.8.0',+ '0.8.0',+ [+ ['0.8.0', false],+ ['0.7.1', false],+ ],+ ],+ ['0.7.1', '0.7.1', [['0.7.1', false]]],+ [+ '0.7.1-canary.def5678',+ '0.7.1',+ [+ ['0.7.1', false],+ ['0.7.1-canary.def5678', true],+ ],+ ],+ [+ '0.7.2-canary.def5678',+ '0.7.1',+ [+ ['0.7.2-canary.def5678', true],+ ['0.7.1', false],+ ],+ ],+ ]) {+ const dir = fs.mkdtempSync(path.join(cacheDir, 'core-'));+ const entry = find(+ officialList({version: '0.7.1', project: withCore(dir, core)}).packages,+ NEUTRAL,+ );+ expect(versionsOf(entry), core).toEqual({latest, versions});+ expect(entry.pin, core).toBe(core);+ }+ });++ it('pins the Core version or range a fresh clone declares, and nothing for another spec', () => {+ const p = project({cwd: path.join(cacheDir, 'src')});+ for (const [spec, pin, versions] of [+ [+ '0.6.8',+ '0.6.8',+ [+ ['0.7.1', false],+ ['0.6.8', false],+ ],+ ],+ [+ '=0.6.8',+ '0.6.8',+ [+ ['0.7.1', false],+ ['0.6.8', false],+ ],+ ],+ ['^0.6.8', '^0.6.8', [['0.7.1', false]]],+ ['>=0.6.8 <0.8.0', '>=0.6.8 <0.8.0', [['0.7.1', false]]],+ ['0.6.x || ^0.7.0', '0.6.x || ^0.7.0', [['0.7.1', false]]],+ // A space after an operator: node-semver reads both as >=0.6.8 <0.7.0.+ ['~ 0.6.8', '~0.6.8', [['0.7.1', false]]],+ ['>= 0.6.8 < 0.7.0', '>=0.6.8 <0.7.0', [['0.7.1', false]]],+ ['workspace:*', '0.7.1', [['0.7.1', false]]],+ ['file:../core', '0.7.1', [['0.7.1', false]]],+ ['latest', '0.7.1', [['0.7.1', false]]],+ ]) {+ fs.writeFileSync(+ path.join(cacheDir, 'package.json'),+ JSON.stringify({devDependencies: {'@astryxdesign/core': spec}}),+ );+ const entry = find(+ officialList({version: '0.7.1', project: p}).packages,+ NEUTRAL,+ );+ expect(versionsOf(entry), spec).toEqual({latest: '0.7.1', versions});+ expect(entry.pin, spec).toBe(pin);+ }+ });++ it('on a canary CLI with no Core, pins only the canary-only packages', () => {+ const canary = officialList({+ version: '0.7.2-canary.abc1234',+ project: project({cwd: cacheDir}),+ }).packages;+ expect(versionsOf(find(canary, NEUTRAL))).toEqual({+ latest: null,+ versions: [],+ });+ expect(find(canary, NEUTRAL).pin).toBeUndefined();+ const names = canaryOnlyNames();+ expect(names.length).toBeGreaterThan(0);+ for (const name of names) {+ expect(versionsOf(find(canary, name)), name).toEqual({+ latest: null,+ versions: [['0.7.2-canary.abc1234', true]],+ });+ expect(find(canary, name).pin, name).toBe('0.7.2-canary.abc1234');+ }+ });++ it('lists the canary-only packages beside a canary Core, never beside a released one', () => {+ const released = officialList({+ version: '0.7.2-canary.abc1234',+ project: withCore(cacheDir, '0.7.1'),+ }).packages;+ expect(versionsOf(find(released, NEUTRAL))).toEqual({+ latest: '0.7.1',+ versions: [['0.7.1', false]],+ });+ for (const name of canaryOnlyNames()) {+ expect(find(released, name), name).toBeUndefined();+ }++ fs.writeFileSync(+ path.join(cacheDir, 'package.json'),+ JSON.stringify({dependencies: {'@astryxdesign/core': '^0.7.0'}}),+ );+ const declared = officialList({+ version: '0.7.2-canary.abc1234',+ project: project({cwd: cacheDir}),+ }).packages;+ for (const name of canaryOnlyNames()) {+ expect(find(declared, name), name).toBeUndefined();+ }++ const beside = officialList({+ version: '0.7.2-canary.abc1234',+ project: withCore(cacheDir, '0.7.2-canary.def5678'),+ }).packages;+ for (const name of canaryOnlyNames()) {+ expect(versionsOf(find(beside, name)), name).toEqual({+ latest: null,+ versions: [['0.7.2-canary.def5678', true]],+ });+ }+ });++ it('reads back as a valid discover catalog on a release and a canary CLI', () => {+ for (const version of ['0.7.1', '0.7.2-canary.abc1234']) {+ const packages = officialList({version}).packages.map(+ ({pin: _pin, ...entry}) => entry,+ );+ const parsed = parseDiscoverCatalog(+ catalog('Astryx', packages),+ 'the official list',+ );+ expect(parsed.packages).toEqual(packages);+ }+ });++ it('reports a list it cannot read instead of throwing', () => {+ const result = officialList({+ file: path.join(cacheDir, 'missing.json'),+ version: '0.7.1',+ });+ expect(result.packages).toEqual([]);+ expect(result.error).toContain('the official list could not be read');+ });++ it('pins what each entry names, quoting a range, and the pin is a version it lists', () => {+ for (const [cli, core, declared] of [+ ['0.7.1', '0.6.8', undefined],+ ['0.7.1', '0.8.0', undefined],+ ['0.7.1', undefined, '^0.6.8'],+ ['0.7.1', undefined, '>=0.6.8 <0.8.0'],+ ['0.7.2-canary.abc1234', undefined, undefined],+ ['0.7.2-canary.abc1234', '0.7.2-canary.def5678', undefined],+ ]) {+ const dir = fs.mkdtempSync(path.join(cacheDir, 'pin-'));+ if (declared) {+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({dependencies: {'@astryxdesign/core': declared}}),+ );+ }+ const p = core ? withCore(dir, core) : project({cwd: dir});+ const {packages} = officialList({version: cli, project: p});+ const add = addCommand(p, {official: packages});+ for (const entry of packages) {+ const label = `${cli} ${core ?? declared} ${entry.package}`;+ const command = add(entry.package);+ if (entry.pin == null) {+ expect(command.endsWith(` ${entry.package}`), label).toBe(true);+ } else if (entry.versions.some(v => v.version === entry.pin)) {+ expect(+ command.endsWith(` ${entry.package}@${entry.pin}`),+ label,+ ).toBe(true);+ } else {+ // Only a declared range is pinned without being a listed version.+ expect(entry.pin, label).toBe(declared);+ expect(+ command.endsWith(` "${entry.package}@${declared}"`),+ label,+ ).toBe(true);+ }+ }+ }+ });+});++describe('officialDeclarations', () => {+ const list = [+ official('@astryxdesign/theme-gothic'),+ official('@astryxdesign/theme-matcha'),+ official('@astryxdesign/theme-stone'),+ ];++ it('reads the project’s own package.json from a subfolder, aliases included, and keeps peers apart', () => {+ fs.writeFileSync(+ path.join(cacheDir, 'package.json'),+ JSON.stringify({+ dependencies: {+ 'my-gothic': 'npm:@astryxdesign/[email protected]',+ react: '19.0.0',+ },+ devDependencies: {'@astryxdesign/theme-matcha': '0.7.0'},+ peerDependencies: {'@astryxdesign/theme-stone': '>=0.7.0'},+ }),+ );+ const declared = officialDeclarations(+ project({cwd: path.join(cacheDir, 'src', 'components')}),+ list,+ );+ expect([...declared.dependency]).toEqual([+ ['@astryxdesign/theme-gothic', 'my-gothic'],+ ['@astryxdesign/theme-matcha', '@astryxdesign/theme-matcha'],+ ]);+ expect([...declared.any].sort()).toEqual([+ '@astryxdesign/theme-gothic',+ '@astryxdesign/theme-matcha',+ '@astryxdesign/theme-stone',+ ]);+ });+});++describe('withDeclaredOfficial', () => {+ /** @param {string} dir @param {string} name @param {string} version */+ function install(dir, name, version) {+ const at = path.join(dir, 'node_modules', ...name.split('/'));+ fs.mkdirSync(at, {recursive: true});+ fs.writeFileSync(+ path.join(at, 'package.json'),+ JSON.stringify({name, version}),+ );+ }++ /** @param {object[]} packages */+ const result = packages => ({sources: [], packages});+ /** @param {Array<[string, string]>} entries */+ const declares = entries => ({+ dependency: new Map(entries),+ any: new Set(entries.map(([name]) => name)),+ });+ const gothic = {+ ...official('@astryxdesign/theme-gothic', {description: 'Dark.'}),+ source: 'Astryx',+ official: true,+ };++ it('counts a declared official package as installed, first, with its installed version', () => {+ install(cacheDir, '@astryxdesign/theme-gothic', '0.7.0');+ const installed = withDeclaredOfficial(+ project({cwd: cacheDir}),+ [{name: '@acme/ui', category: '@acme/ui', components: []}],+ result([gothic]),+ declares([['@astryxdesign/theme-gothic', '@astryxdesign/theme-gothic']]),+ [gothic],+ );+ expect(installed).toEqual([+ {+ name: '@astryxdesign/theme-gothic',+ category: '@astryxdesign/theme-gothic',+ version: '0.7.0',+ description: 'Dark.',+ components: [],+ themes: ['gothic'],+ declaredOfficial: true,+ },+ {name: '@acme/ui', category: '@acme/ui', components: []},+ ]);+ });++ it('reads the version of a package installed under an npm alias', () => {+ install(cacheDir, 'my-gothic', '0.6.8');+ const [entry] = withDeclaredOfficial(+ project({cwd: cacheDir}),+ [],+ result([gothic]),+ declares([['@astryxdesign/theme-gothic', 'my-gothic']]),+ [gothic],+ );+ expect(entry).toMatchObject({+ name: '@astryxdesign/theme-gothic',+ version: '0.6.8',+ });+ });++ it('leaves a declared official package alone when another source supplied its entry', () => {+ const fromOwn = {...gothic, source: 'Own', official: undefined};+ expect(+ withDeclaredOfficial(+ project({cwd: cacheDir}),+ [],+ result([fromOwn]),+ declares([+ ['@astryxdesign/theme-gothic', '@astryxdesign/theme-gothic'],+ ]),+ [gothic],+ ),+ ).toEqual([]);+ });++ it('leaves out an official integration that failed to load, even when declared', () => {+ expect(+ withDeclaredOfficial(+ project({+ cwd: cacheDir,+ integrations: [+ {name: '@astryxdesign/theme-gothic', __loadError: 'x'},+ ],+ }),+ [],+ result([gothic]),+ declares([+ ['@astryxdesign/theme-gothic', '@astryxdesign/theme-gothic'],+ ]),+ [gothic],+ ),+ ).toEqual([]);+ });+});++describe('addCommand with the official list', () => {+ const list = [+ official('@astryxdesign/theme-gothic', {pin: '0.6.8'}),+ official('@astryxdesign/theme-matcha', {pin: '^0.6.8'}),+ official('@astryxdesign/theme-stone', {pin: undefined}),+ official('@astryxdesign/charts', {pin: '0.7.2-canary.abc1234'}),+ ];+ const add = () => addCommand(project({cwd: cacheDir}), {official: list});++ it('pins what an official entry names, quoting a range', () => {+ const command = add();+ expect(command('@astryxdesign/theme-gothic')).toMatch(+ / @astryxdesign\/theme-gothic@0\.6\.8$/,+ );+ expect(command('@astryxdesign/theme-matcha')).toMatch(+ / "@astryxdesign\/theme-matcha@\^0\.6\.8"$/,+ );+ expect(command('@astryxdesign/theme-stone')).toMatch(+ / @astryxdesign\/theme-stone$/,+ );+ expect(command('@astryxdesign/charts')).toMatch(+ / @astryxdesign\/charts@0\.7\.2-canary\.abc1234$/,+ );+ });++ it('adds a version that was asked for, and leaves other packages alone', () => {+ const command = add();+ expect(command('@acme/ui')).toMatch(/ @acme\/ui$/);+ expect(command('@astryxdesign/theme-matcha', '0.7.1')).toMatch(+ / @astryxdesign\/theme-matcha@0\.7\.1$/,+ );});});diff --git a/packages/cli/api/discover/_catalog-view.mjs b/packages/cli/api/discover/_catalog-view.mjsindex b97f665099..2d74f707d1 100644--- a/packages/cli/api/discover/_catalog-view.mjs+++ b/packages/cli/api/discover/_catalog-view.mjs@@ -59,15 +59,24 @@ export function hasKind(entry, kind) {}/**- * Where a catalog package stands against the project.+ * Where a catalog package stands against the project. An entry the official+ * list supplied is checked against the project's own package.json+ * (`officialDeclared`); any other entry against the folder discover runs in+ * (`declared`).* @param {CatalogPackage} pkg* @param {Set<string>} installedNames* @param {Set<string>} declared+ * @param {Set<string>} [officialDeclared]* @returns {{state: 'installed' | 'declared' | 'alias' | 'available', installedAs?: string}}*/-export function catalogState(pkg, installedNames, declared) {+export function catalogState(pkg, installedNames, declared, officialDeclared) {if (installedNames.has(pkg.package)) return {state: 'installed'};- if (declared.has(pkg.package)) return {state: 'declared'};+ if (+ (pkg.official && officialDeclared ? officialDeclared : declared).has(+ pkg.package,+ )+ )+ return {state: 'declared'};const installedAs = pkg.aliases.find(name => installedNames.has(name) || declared.has(name),);@@ -103,18 +112,28 @@ export function catalogEntry(pkg, version) {/*** What the project could add: every catalog package it does not have, once per- * integration (the first name a source lists), never an alias of one it has.+ * integration (the first name a source lists), never an alias of one it has,+ * each with the command that adds it when `install` is given.* @param {CatalogResult} catalog* @param {InstalledPackage[]} installed* @param {Set<string>} declared+ * @param {{officialDeclared?: Set<string>, install?: (pkg: CatalogPackage) => string}} [options]*/-export function availableEntries(catalog, installed, declared) {+export function availableEntries(+ catalog,+ installed,+ declared,+ {officialDeclared, install} = {},+) {const installedNames = new Set(installed.map(p => p.name));/** @type {Set<string>} */const integrations = new Set();const entries = [];for (const pkg of catalog.packages) {- if (catalogState(pkg, installedNames, declared).state !== 'available')+ if (+ catalogState(pkg, installedNames, declared, officialDeclared).state !==+ 'available'+ )continue;if (integrations.has(pkg.integration)) continue;integrations.add(pkg.integration);@@ -124,6 +143,7 @@ export function availableEntries(catalog, installed, declared) {...entry,...(pkg.aliases.length > 0 ? {aliases: pkg.aliases} : {}),source: pkg.source,+ ...(install ? {install: install(pkg)} : {}),});}return entries;@@ -150,9 +170,10 @@ export function withLatest(installed, catalog) {* @param {InstalledPackage[]} installed* @param {CatalogResult} catalog* @param {Set<string>} declared+ * @param {Set<string>} [officialDeclared]* @returns {SearchItem[]}*/-export function searchItems(installed, catalog, declared) {+export function searchItems(installed, catalog, declared, officialDeclared) {/** @type {SearchItem[]} */const items = [];for (const pkg of installed) {@@ -176,7 +197,10 @@ export function searchItems(installed, catalog, declared) {/** @type {Set<string>} */const integrations = new Set();for (const pkg of catalog.packages) {- if (catalogState(pkg, installedNames, declared).state !== 'available')+ if (+ catalogState(pkg, installedNames, declared, officialDeclared).state !==+ 'available'+ )continue;if (integrations.has(pkg.integration)) continue;integrations.add(pkg.integration);diff --git a/packages/cli/api/discover/discover.doc.mjs b/packages/cli/api/discover/discover.doc.mjsindex 9e591c3149..84c63ac0bf 100644--- a/packages/cli/api/discover/discover.doc.mjs+++ b/packages/cli/api/discover/discover.doc.mjs@@ -14,10 +14,11 @@ export const doc = {namespace: 'cli/api',displayName: 'discover()',summary:- 'Browse and search integrations: the ones a project has and, through discover sources, the ones it could add.',+ 'Browse and search integrations: the ones a project has and, through the official list and discover sources, the ones it could add.',description:- 'Lists the integrations a project loads and, when the project or an integration provides a discover source, ' +- 'the packages it could add, with what each one adds per kind. An @scope/name query shows one package with every ' ++ 'Lists the integrations a project loads and the official packages it declares, then the packages it could add: ' ++ 'the official Astryx packages first, from the list the CLI carries, then whatever the discover sources of the ' ++ 'project and its integrations list, with what each one adds per kind. An @scope/name query shows one package with every ' +'version its source knows; @scope/name@version shows one version; @scope/name/Component returns an installed ' +"component's validated doc, and any other item path returns that item. A free-text term searches every item and " +'package. Discover only reads: it prints the command that adds a package and never runs it.',@@ -89,12 +90,12 @@ export const doc = {{type: 'discover.list',description:- 'The installed integrations (name, category, components, version, and a list per other kind they add). With a discover source, meta.available lists what the project could add and meta.sources reports each source. When the list is empty it carries meta.configured.',+ '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, and 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.',+ "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.",},{type: 'discover.detail.doc',@@ -123,7 +124,7 @@ export const doc = {},{code: 'ERR_UNKNOWN_PACKAGE',- when: 'neither the project nor any discover source has the package',+ when: 'neither the project, the official list, nor any discover source has the package',},{code: 'ERR_UNKNOWN_COMPONENT',diff --git a/packages/cli/api/discover/discover.mjs b/packages/cli/api/discover/discover.mjsindex 4652a5c562..9b0128bb0a 100644--- a/packages/cli/api/discover/discover.mjs+++ b/packages/cli/api/discover/discover.mjs@@ -4,7 +4,8 @@* @file Programmatic API for the discover command — dispatcher + barrel.** `discover()` browses the integrations a project has and, through discover- * sources, the ones it could add. It only reads: the package manager installs.+ * sources and the official list the CLI carries, the ones it could add. It+ * only reads: the package manager installs.* Its job is to resolve the project and its sources (via ./_adapter) and route* to the leaf that owns each response shape:*@@ -22,6 +23,7 @@* the discover leaves.*/+export {OFFICIAL_SOURCE_NAME} from './_adapter.mjs';import {addCommand,callSources,@@ -30,6 +32,10 @@ import {discoverPackages,findComponent,hasSources,+ officialDeclarations,+ officialFirst,+ officialList,+ withDeclaredOfficial,} from './_adapter.mjs';import {availableEntries,@@ -49,9 +55,6 @@ import {DISCOVER_KINDS} from '../../authoring/discover/parse.mjs';const DEFAULT_LIMIT = 20;-/** @type {import('./_adapter.mjs').CatalogResult} */-const NO_CATALOG = {sources: [], packages: []};-/*** Split a package-shaped query: `name`, `name@version`, or `name/item`, with an* optional `@scope/` prefix on the name.@@ -144,6 +147,23 @@ function similarItems(entry, wanted) {}));}+/**+ * Whether discover answers a query in this project, or answers every query+ * with the list (spec:AST-051 FR1): it answers once the project loads an+ * integration or has a discover source of its own. This is the rule+ * `discover()` applies to the project it loads; the command reads it to keep+ * the list's hints from suggesting queries that only return the list.+ * @param {import('../../foundation/config/project.mjs').Project | undefined} project+ * @returns {boolean}+ */+export function answersQueries(project) {+ return (+ project != null &&+ (project.loadedIntegrations.some(i => !i.__loadError) ||+ hasSources(project))+ );+}+/*** @param {string} [query]* @param {import('./discover.type.mjs').DiscoverOptions} [options]@@ -165,24 +185,49 @@ export async function discover(query, options = {}) {: undefined;const {packages: scanned, configured, project} = await discoverPackages();- const withSources = hasSources(project);- const packages = await describeInstalled(project, scanned);+ const integrations = await describeInstalled(project, scanned);const declared = declaredDependencies(project);+ // The official list is always read, so discover always has a source.+ const official = officialList({project});+ const declarations = officialDeclarations(project, official.packages);const add = addCommand(project);+ const addOfficial = addCommand(project, {official: official.packages});+ /** @param {{package: string, official?: true}} pkg */+ const installFor = pkg => (pkg.official ? addOfficial : add)(pkg.package);/** @param {{package?: string, version?: string}} [request] */- const catalogFor = async request =>- withSources ? await callSources(project, request) : NO_CATALOG;+ const catalogFor = request => callSources(project, request, {official});+ /**+ * What the project has, once a catalog says which official packages it+ * declares.+ * @param {import('./_adapter.mjs').CatalogResult} catalog+ */+ const installedFor = catalog =>+ withDeclaredOfficial(+ project,+ integrations,+ catalog,+ declarations,+ official.packages,+ );- // No query, or nothing to look through: the list.- if (!query || (packages.length === 0 && !withSources)) {- if (!withSources) return list(packages, {configured, type, only});+ // No query, or any query in a project that loads no integration and has no+ // discover source of its own: the list (spec:AST-051 FR1).+ if (!query || (integrations.length === 0 && !hasSources(project))) {const catalog = await catalogFor();+ const packages = installedFor(catalog);return list(withLatest(packages, catalog), {configured,type,only,- available: availableEntries(catalog, packages, declared),+ available: officialFirst(+ availableEntries(catalog, packages, declared, {+ officialDeclared: declarations.any,+ install: installFor,+ }),+ official.packages,+ entry => entry.name,+ ),sources: catalog.sources,});}@@ -199,7 +244,6 @@ export async function discover(query, options = {}) {}const target = splitTarget(query);- const installedNames = new Set(packages.map(p => p.name));/*** One package, one version, or one item, once `target.name` is known to be@@ -207,29 +251,72 @@ export async function discover(query, options = {}) {* @param {import('./_adapter.mjs').CatalogResult} catalog*/const packageView = async catalog => {+ const packages = installedFor(catalog);+ const installedNames = new Set(packages.map(p => p.name));const entry = catalog.packages.find(p => p.package === target.name);const installedAs = entry- ? catalogState(entry, installedNames, declared).installedAs+ ? catalogState(entry, installedNames, declared, declarations.any)+ .installedAs: undefined;- const context = {catalog: entry, version: target.version, add, installedAs};+ const isIntegration = integrations.some(p => p.name === target.name);+ // An entry only the official list supplies answers for what it lists.+ // Any other version or item of that package keeps the answer discover+ // gave before the list existed: ERR_UNKNOWN_PACKAGE.+ const officialOnly = entry?.official === true && !isIntegration;+ if (officialOnly && target.version) {+ const local = packages.find(p => p.name === target.name)?.version;+ if (+ target.version !== local &&+ !entry.versions.some(v => v.version === target.version)+ ) {+ throw new AstryxError(+ `${target.name}@${target.version} is not a version discover knows here: ${+ entry.versions.length > 0+ ? `it knows ${entry.versions.map(v => v.version).join(', ')}`+ : 'it knows no version of it for this project'+ }. Other versions are on the package registry.`,+ [...new Set([...entry.versions.map(v => v.version), local])]+ .filter(v => v != null)+ .map(v => ({+ name: `${target.name}@${v}`,+ reason: 'version discover knows',+ })),+ ERROR_CODES.ERR_UNKNOWN_PACKAGE,+ );+ }+ }+ const context = {+ catalog: entry,+ version: target.version,+ // Only an entry the official list supplied gets a pinned version.+ add: entry?.official ? addOfficial : add,+ installedAs,+ };if (!target.item) return detail(packages, target.name, context);const found = item(packages, target.name, target.item, context);if (found) return found;+ if (officialOnly) {+ throw new AstryxError(+ `"${target.item}" not found in ${target.name}`,+ similarItems(entry, target.item),+ ERROR_CODES.ERR_UNKNOWN_PACKAGE,+ );+ }// Only an installed package has docs to fall back to. For one that is// only in a source, the item is what is unknown, not the package.- if (entry && !packages.some(p => p.name === target.name)) {+ if (entry && !isIntegration) {throw new AstryxError(`"${target.item}" not found in ${target.name}`,similarItems(entry, target.item),ERROR_CODES.ERR_UNKNOWN_COMPONENT,);}- return await doc(packages, target.name, target.item, {lang, zh});+ return await doc(integrations, target.name, target.item, {lang, zh});};// An installed component keeps resolving to its full doc, before any source// is asked anything.- const installedPkg = packages.find(p => p.name === target.name);+ const installedPkg = integrations.find(p => p.name === target.name);if (installedPkg && target.item && !target.version) {const resolved = findComponent([installedPkg], target.item);if (resolved) return await docFromResult(resolved, {lang, zh});@@ -251,8 +338,9 @@ export async function discover(query, options = {}) {);}+ const packages = installedFor(listing);return await search(packages, query, {- items: searchItems(packages, listing, declared),+ items: searchItems(packages, listing, declared, declarations.any),type,only,limit: limit ?? DEFAULT_LIMIT,diff --git a/packages/cli/api/discover/discover.type.mjs b/packages/cli/api/discover/discover.type.mjsindex cb3d7a9a94..8363a2fcdc 100644--- a/packages/cli/api/discover/discover.type.mjs+++ b/packages/cli/api/discover/discover.type.mjs@@ -21,23 +21,27 @@* astryx --json discover* @typedef {object} DiscoverListResponse* @property {'discover.list'} type- * @property {DiscoverListEntry[]} data The integrations the project loads.+ * @property {DiscoverListEntry[]} data What the project has: the integrations+ * it loads and the official packages it declares, official packages first.* @property {DiscoverListMeta} [meta] Present when the list is empty, and- * whenever the project has a discover source.+ * whenever discover has a source, which is always: the official list the CLI+ * carries is one.*//*** @typedef {object} DiscoverListMeta- * @property {boolean} [configured] Present when `data` is empty, so callers can+ * @property {boolean} [configured] Present when `data` lists no integration (a+ * declared official package is not one), so callers can* distinguish "no packages configured" from "configured but nothing* discovered".* @property {DiscoverAvailableEntry[]} [available] What the project could add,- * one entry per integration, never an alias of a package it has.+ * one entry per integration, never an alias of a package it has; official+ * packages first.* @property {DiscoverSourceState[]} [sources] What each discover source did.*//**- * An installed integration.+ * An installed integration, or an official package the project declares.* @typedef {object} DiscoverListEntry* @property {string} name* @property {string} category@@ -66,13 +70,17 @@* @property {string[]} [agentDocs]* @property {string} [description]* @property {string[]} [aliases] The integration's other package names.- * @property {string} source The discover source that lists it.+ * @property {string} source The discover source that lists it; `Astryx` for+ * the official list.+ * @property {string} [install] The package-manager command that adds it;+ * discover prints it and never runs it.*//*** @typedef {object} DiscoverSourceState* @property {string} name- * @property {string} from `astryx.config`, or the integration that exports it.+ * @property {string} from `astryx.config`, the integration that exports it, or+ * `@astryxdesign/cli` for the official list.* @property {'fresh' | 'saved' | 'failed'} status `saved`: the live call* failed and discover used the copy saved at `savedAt`.* @property {string} [generatedAt]diff --git a/packages/cli/api/discover/list/list.mjs b/packages/cli/api/discover/list/list.mjsindex 97f1a61ea1..0a007832e5 100644--- a/packages/cli/api/discover/list/list.mjs+++ b/packages/cli/api/discover/list/list.mjs@@ -12,9 +12,10 @@ import {toEntry} from '../_adapter.mjs';import {hasKind} from '../_catalog-view.mjs';/**- * Build the discover.list response. `data` lists installed integrations. An- * empty `data` carries `meta.configured`, so callers can distinguish "nothing- * configured" from "configured but nothing discovered". With discover sources,+ * Build the discover.list response. `data` lists installed integrations and+ * the official packages the project declares. A `data` with no integration+ * carries `meta.configured`, so callers can distinguish "nothing configured"+ * from "configured but nothing discovered". With discover sources,* `meta.available` lists what the project could add and `meta.sources` reports* what each source did.*@@ -31,18 +32,24 @@ import {hasKind} from '../_catalog-view.mjs';export function list(packages, {configured, available, sources, type, only}) {const keep = (/** @type {Record<string, unknown>} */ entry) =>type == null || hasKind(entry, type);- const data =+ const shown =only === 'available'? []- : packages- .map(toEntry)- .filter(entry =>- keep(/** @type {Record<string, unknown>} */ (entry)),- );+ : packages.filter(pkg =>+ keep(/** @type {Record<string, unknown>} */ (toEntry(pkg))),+ );+ const data = shown.map(toEntry);/** @type {Record<string, unknown>} */const meta = {};- if (data.length === 0) meta.configured = configured;+ // An official package the project declares is not an integration, so it+ // never hides whether any integration is configured.+ if (+ !shown.some(+ pkg => !(/** @type {{declaredOfficial?: true}} */ (pkg).declaredOfficial),+ )+ )+ meta.configured = configured;if (sources !== undefined) {meta.available = only === 'installed' ? [] : (available ?? []).filter(keep);meta.sources = sources;diff --git a/packages/cli/assets/discover/official-packages.json b/packages/cli/assets/discover/official-packages.jsonnew file mode 100644index 0000000000..d1e65e928c--- /dev/null+++ b/packages/cli/assets/discover/official-packages.json@@ -0,0 +1,363 @@+{+ "packages": [+ {+ "package": "@astryxdesign/charts",+ "description": "Astryx charts — a config-model data visualization library (d3-based). Published to npm only under the @canary dist-tag for early testing; never released as a stable (latest) version.",+ "canaryOnly": true,+ "contributions": [+ {+ "kind": "component",+ "name": "Chart"+ },+ {+ "kind": "component",+ "name": "ChartAxis"+ },+ {+ "kind": "component",+ "name": "ChartGrid"+ },+ {+ "kind": "component",+ "name": "ChartLegend"+ },+ {+ "kind": "component",+ "name": "ChartSwatch"+ },+ {+ "kind": "component",+ "name": "ChartTooltip"+ },+ {+ "kind": "template",+ "name": "ChartShowcase"+ },+ {+ "kind": "template",+ "name": "ChartTrendComparison"+ }+ ]+ },+ {+ "package": "@astryxdesign/lab",+ "description": "Experimental Astryx components — published to npm only under the @canary dist-tag for early testing; never released as a stable (latest) version.",+ "canaryOnly": true,+ "contributions": [+ {+ "kind": "component",+ "name": "ChartArea"+ },+ {+ "kind": "component",+ "name": "ChartBar"+ },+ {+ "kind": "component",+ "name": "ChartCandlestick"+ },+ {+ "kind": "component",+ "name": "ChartDot"+ },+ {+ "kind": "component",+ "name": "ChartDotGL"+ },+ {+ "kind": "component",+ "name": "ChartDotGLInteractive"+ },+ {+ "kind": "component",+ "name": "ChartHeatmapGL"+ },+ {+ "kind": "component",+ "name": "ChartLine"+ },+ {+ "kind": "component",+ "name": "ChartStreamGL"+ },+ {+ "kind": "component",+ "name": "ChatEmojiPicker"+ },+ {+ "kind": "component",+ "name": "ChatReactionBar"+ },+ {+ "kind": "component",+ "name": "ChatReasoning"+ },+ {+ "kind": "component",+ "name": "ChatTypingIndicator"+ },+ {+ "kind": "component",+ "name": "ChatUnreadDivider"+ },+ {+ "kind": "component",+ "name": "CircularProgress"+ },+ {+ "kind": "component",+ "name": "CodeEditor"+ },+ {+ "kind": "component",+ "name": "CommentComposer"+ },+ {+ "kind": "component",+ "name": "CommentPin"+ },+ {+ "kind": "component",+ "name": "Comments"+ },+ {+ "kind": "component",+ "name": "CommentThread"+ },+ {+ "kind": "component",+ "name": "DiffViewer"+ },+ {+ "kind": "component",+ "name": "EmojiPicker"+ },+ {+ "kind": "component",+ "name": "InfoTip"+ },+ {+ "kind": "component",+ "name": "ListInput"+ },+ {+ "kind": "component",+ "name": "LogStream"+ },+ {+ "kind": "component",+ "name": "MobileTokenizer"+ },+ {+ "kind": "component",+ "name": "RadialChart"+ },+ {+ "kind": "component",+ "name": "SankeyChart"+ },+ {+ "kind": "component",+ "name": "Schedule"+ },+ {+ "kind": "component",+ "name": "Stat"+ },+ {+ "kind": "component",+ "name": "SVGIcon"+ },+ {+ "kind": "component",+ "name": "ThreeDBar"+ },+ {+ "kind": "component",+ "name": "ThreeDChart"+ },+ {+ "kind": "component",+ "name": "ThreeDScatter"+ },+ {+ "kind": "component",+ "name": "ThreeDScatterGL"+ },+ {+ "kind": "component",+ "name": "ThreeDSurface"+ },+ {+ "kind": "component",+ "name": "Tour"+ },+ {+ "kind": "component",+ "name": "TransferList"+ },+ {+ "kind": "template",+ "name": "CommentComposerShowcase"+ },+ {+ "kind": "template",+ "name": "CommentPinInMargin"+ },+ {+ "kind": "template",+ "name": "CommentPinShowcase"+ },+ {+ "kind": "template",+ "name": "CommentsInCard"+ },+ {+ "kind": "template",+ "name": "CommentsInline"+ },+ {+ "kind": "template",+ "name": "CommentsShowcase"+ },+ {+ "kind": "template",+ "name": "CommentThreadInPopover"+ },+ {+ "kind": "template",+ "name": "CommentThreadShowcase"+ },+ {+ "kind": "template",+ "name": "DiffViewerShowcase"+ },+ {+ "kind": "template",+ "name": "EmojiPickerInPopover"+ },+ {+ "kind": "template",+ "name": "EmojiPickerShowcase"+ }+ ]+ },+ {+ "package": "@astryxdesign/richtext",+ "description": "Astryx rich text — a Lexical-based rich text editor and viewer, styled with Astryx design tokens.",+ "releasedWithCore": true,+ "contributions": [+ {+ "kind": "component",+ "name": "RichTextEditor"+ },+ {+ "kind": "template",+ "name": "RichTextEditorShowcase"+ }+ ]+ },+ {+ "package": "@astryxdesign/theme-butter",+ "description": "Warm, creamy yellows with a friendly blue accent. Playful enough for consumer surfaces, soft enough to stay readable.",+ "releasedWithCore": true,+ "contributions": [+ {+ "kind": "theme",+ "name": "butter",+ "title": "Butter",+ "summary": "Warm, creamy yellows with a friendly blue accent. Playful enough for consumer surfaces, soft enough to stay readable."+ }+ ]+ },+ {+ "package": "@astryxdesign/theme-chocolate",+ "description": "Warm chocolate theme for Astryx — rich brown palette with Fraunces headings, Albert Sans body, and Lucide icons",+ "releasedWithCore": true,+ "contributions": [+ {+ "kind": "theme",+ "name": "chocolate",+ "title": "Chocolate",+ "summary": "Warm chocolate theme for Astryx — rich brown palette with Fraunces headings, Albert Sans body, and Lucide icons"+ }+ ]+ },+ {+ "package": "@astryxdesign/theme-gothic",+ "description": "Deep blue-grays and a signature display serif. Dramatic and editorial, for surfaces that want to be remembered.",+ "releasedWithCore": true,+ "contributions": [+ {+ "kind": "theme",+ "name": "gothic",+ "title": "Gothic",+ "summary": "Deep blue-grays and a signature display serif. Dramatic and editorial, for surfaces that want to be remembered."+ }+ ]+ },+ {+ "package": "@astryxdesign/theme-matcha",+ "description": "Earthy greens with a calm, organic feel. Naturalistic and grounded, great for wellness or content-first apps.",+ "releasedWithCore": true,+ "contributions": [+ {+ "kind": "theme",+ "name": "matcha",+ "title": "Matcha",+ "summary": "Earthy greens with a calm, organic feel. Naturalistic and grounded, great for wellness or content-first apps."+ }+ ]+ },+ {+ "package": "@astryxdesign/theme-neutral",+ "description": "Restrained warm grays. Minimal and quiet, so the content stays the focus.",+ "releasedWithCore": true,+ "contributions": [+ {+ "kind": "theme",+ "name": "neutral",+ "title": "Neutral",+ "summary": "Restrained warm grays. Minimal and quiet, so the content stays the focus."+ }+ ]+ },+ {+ "package": "@astryxdesign/theme-stone",+ "description": "Warm stone and slate, earthy and understated, with just enough character to feel handcrafted.",+ "releasedWithCore": true,+ "contributions": [+ {+ "kind": "theme",+ "name": "stone",+ "title": "Stone",+ "summary": "Warm stone and slate, earthy and understated, with just enough character to feel handcrafted."+ }+ ]+ },+ {+ "package": "@astryxdesign/theme-y2k",+ "description": "Hot pinks, lime greens, and Poppins. Bubbly, playful, and unmistakably retro.",+ "releasedWithCore": true,+ "contributions": [+ {+ "kind": "theme",+ "name": "y2k",+ "title": "Y2K",+ "summary": "Hot pinks, lime greens, and Poppins. Bubbly, playful, and unmistakably retro."+ }+ ]+ },+ {+ "package": "@astryxdesign/vega",+ "description": "Astryx Vega wrapper — chart and data visualization components. Published to npm only under the @canary dist-tag for early testing; never released as a stable (latest) version.",+ "canaryOnly": true,+ "contributions": [+ {+ "kind": "component",+ "name": "VegaChart"+ }+ ]+ }+ ]+}diff --git a/packages/cli/authoring/discover/discover.doc.mjs b/packages/cli/authoring/discover/discover.doc.mjsindex d251ff1a68..8f1cbf0881 100644--- a/packages/cli/authoring/discover/discover.doc.mjs+++ b/packages/cli/authoring/discover/discover.doc.mjs@@ -16,7 +16,7 @@ export const doc = {displayName: 'DiscoverSource',namespace: 'authoring',description:- 'A source for `astryx discover`: an async function that returns a catalog of packages a project could add, their versions, and what each version adds. Set it as `discover` in astryx.config, or export it as `discover` from an integration manifest. Discover calls every source, the project one first, and one that throws, runs past 30 seconds, or returns an invalid catalog never hides the others; discover then uses the last good answer that source gave for the same request, or reports the source as failed when it saved none. Discover only reads: it prints the command that adds a package and never runs it.',+ 'A source for `astryx discover`: an async function that returns a catalog of packages a project could add, their versions, and what each version adds. Set it as `discover` in astryx.config, or export it as `discover` from an integration manifest. Discover calls every source, the project one first, and then reads the official list the CLI carries; another source\'s entry for an official package is kept. A source that throws, runs past 30 seconds, or returns an invalid catalog never hides the others; discover then uses the last good answer that source gave for the same request, or reports the source as failed when it saved none. Discover only reads: it prints the command that adds a package and never runs it.',appliesTo:'`discover` in astryx.config.*, or the `discover` named export of astryx.integration.*',fields: [diff --git a/packages/cli/clients/cli/commands/discover.broken-integration.test.mjs b/packages/cli/clients/cli/commands/discover.broken-integration.test.mjsindex cb19040e43..9d8103e524 100644--- a/packages/cli/clients/cli/commands/discover.broken-integration.test.mjs+++ b/packages/cli/clients/cli/commands/discover.broken-integration.test.mjs@@ -83,7 +83,10 @@ describe('astryx discover with a manifest that fails to load', () => {});expect(status).toBe(0);- expect(JSON.parse(stdout).meta).toEqual({configured: true});+ const {meta} = JSON.parse(stdout);+ expect(meta.configured).toBe(true);+ // The official list still answers; nothing else is claimed.+ expect(meta.sources.map(s => s.name)).toEqual(['Astryx']);expect(stderr).not.toContain('integration issue');});});diff --git a/packages/cli/clients/cli/commands/discover.doc.mjs b/packages/cli/clients/cli/commands/discover.doc.mjsindex da7442d053..8f1f61b4f5 100644--- a/packages/cli/clients/cli/commands/discover.doc.mjs+++ b/packages/cli/clients/cli/commands/discover.doc.mjs@@ -17,7 +17,7 @@ export const doc = {summary:'Browse and search integrations: the ones you have and the ones you could add',description:- 'Lists the integrations this project loads and, when it has a discover source, the ones it could add, with what each one adds. ' ++ 'Lists what this project has, the integrations it loads and the official packages it declares, then what it could add: the official Astryx packages first, then whatever its discover sources list, with what each one adds. ' +'A package query shows one package: what it adds, every version a source knows, and the command that adds it. ' +"An @scope/name/Component path prints an installed component's doc; any other item path shows that item. " +'Anything else, even an exact component name, searches every item and package and lists the matches. Discover only reads: your package manager installs, updates, and removes packages.',diff --git a/packages/cli/clients/cli/commands/discover.mjs b/packages/cli/clients/cli/commands/discover.mjsindex d1ba439da1..f3871d862d 100644--- a/packages/cli/clients/cli/commands/discover.mjs+++ b/packages/cli/clients/cli/commands/discover.mjs@@ -27,7 +27,12 @@ import {code,} from '../formatters/index.mjs';import {cliError, rejectEmptyArgument} from '../lib/cli-error.mjs';-import {discover as discoverApi} from '../../../api/discover/discover.mjs';+import {+ answersQueries,+ discover as discoverApi,+ OFFICIAL_SOURCE_NAME,+} from '../../../api/discover/discover.mjs';+import {isValidSemver} from '../../../foundation/env/semver.mjs';import {Project} from '../../../foundation/config/project.mjs';import {warnOnIntegrationIssues} from '../../../foundation/integrations/integration-warnings.mjs';import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';@@ -200,6 +205,72 @@ function versionLines(versions, marks) {});}+/**+ * Whether a package entry adds anything besides themes.+ * @param {Record<string, unknown>} entry+ * @returns {boolean}+ */+function addsMoreThanThemes(entry) {+ return ITEM_FIELDS.some(field => {+ const names = entry[field];+ return field !== 'themes' && Array.isArray(names) && names.length > 0;+ });+}++/**+ * What an official entry's add command installs, when that is not the version+ * the page shows: the project's Core version, or the Core range it declares.+ * @param {string} install the package-manager command+ * @param {string | undefined} shown the version the page shows+ * @param {string | undefined} source the entry's source+ * @returns {string | undefined}+ */+function pinNote(install, shown, source) {+ if (source !== OFFICIAL_SOURCE_NAME) return undefined;+ const pin = /\S@([\d^~<>=*xXv][^"]*)"?$/u.exec(install)?.[1];+ if (pin == null || pin === shown) return undefined;+ return isValidSemver(pin)+ ? `This installs ${pin}, the version that matches this project's Core.`+ : `This installs the newest release in ${pin}, the Core range this project declares.`;+}++/**+ * The "Add it" blocks for a package the project does not have: the command+ * that adds it, then what makes its items usable. A theme still needs+ * `theme add` once the package is installed; anything else loads on the next+ * command.+ * @param {string} install the package-manager command+ * @param {string[]} themes theme slugs the package or item adds+ * @param {boolean} addsOther whether it adds anything besides themes+ * @param {string} run how to invoke the CLI+ * @param {string} [note] what the command installs, when the page shows+ * another version+ * @returns {import('../formatters/index.mjs').Block[]}+ */+function addBlocks(install, themes, addsOther, run, note) {+ /** @type {import('../formatters/index.mjs').Block[]} */+ const blocks = [section('Add it'), code(install)];+ if (note) blocks.push(text(note));+ if (themes.length > 0) {+ blocks.push(+ text(+ themes.length === 1+ ? 'Then use its theme:'+ : 'Then use one of its themes:',+ ),+ code(themes.map(slug => `${run} theme add ${slug}`).join('\n')),+ );+ }+ if (addsOther || themes.length === 0) {+ blocks.push(+ text(+ 'Astryx loads an integration on the next command once it is a dependency.',+ ),+ );+ }+ return blocks;+}+/*** @param {import('commander').Command} program*/@@ -222,8 +293,12 @@ export function registerDiscover(program) {// Non-blocking nudge: if any configured integration has validation// issues, print one compact line to stderr pointing at// doctor integration validate. Best-effort; suppressed in --json mode.+ // Whether a query gets its own answer here or the list (FR1); the+ // list's hints must not suggest queries that only return it again.+ let queries = true;try {const project = await Project.load(process.cwd());+ queries = answersQueries(project);await warnOnIntegrationIssues(project, {json});} catch {// Never let the nudge break the command.@@ -263,71 +338,11 @@ export function registerDiscover(program) {switch (result.type) {case 'discover.list': {const listOpts = itemListOptions(Boolean(options.components));- const available = result.meta?.available;+ // Discover always has a source, the official list, so the list+ // always has an Available side.+ const available = result.meta?.available ?? [];const sources = result.meta?.sources ?? [];- // No discover source: the list of what this project has, as always.- if (available === undefined) {- if (result.data.length === 0) {- if (options.available) {- // The user specifically asked for available packages but- // there is no source to answer from. Say so honestly.- emit(- text('No discover source is configured.'),- text(- [- 'Available integrations are listed by discover sources.',- 'A project can set one in astryx.config.mjs, and installed',- 'integrations can provide one.',- ].join(' '),- ),- text(- [- `Find Astryx packages on npm: npm search @astryxdesign`,- `Learn more: ${run} docs cli/integrations`,- ].join('\n'),- ),- );- } else if (result.meta && result.meta.configured === false) {- emit(- text('No integrations configured.'),- text('Add integration package names to astryx.config.mjs:'),- code(- "export default {\n integrations: ['@scope/your-integration'],\n};",- ),- text(- [- `Find Astryx packages on npm: npm search @astryxdesign`,- `Learn more: ${run} docs cli/integrations`,- ].join('\n'),- ),- );- } else {- emit(- text(- 'No external components found in configured integrations.',- ),- text(- `Find more packages: ${run} discover --available (needs a discover source)`,- ),- );- }- break;- }- emit(- records(result.data, listOpts),- text(- [- 'Usage:',- ` ${run} discover <package> Browse a package`,- ` ${run} discover <package>/Component View component docs`,- ` ${run} discover <search> Search all packages`,- ].join('\n'),- ),- );- break;- }-const kind = options.type? (KIND_PLURALS[options.type] ?? options.type): null;@@ -341,7 +356,9 @@ export function registerDiscover(program) {: text(kind? `None of this project's integrations add ${kind}.`- : 'None yet.',+ : result.meta?.configured+ ? 'No external components found in configured integrations.'+ : 'None yet.',),);}@@ -360,16 +377,44 @@ export function registerDiscover(program) {);}blocks.push(...sourceNotes(sources));- blocks.push(- text(- [- 'Usage:',- ` ${run} discover <package> Browse a package and its versions`,- ` ${run} discover <package>/<item> View one item`,- ` ${run} discover <search> Search every item and package`,- ].join('\n'),- ),- );+ if (!queries) {+ // This project loads no integration and has no discover source+ // of its own, so every query returns this list. Point at the+ // add commands above instead of at queries.+ if (query?.trim()) {+ blocks.push(+ text(+ `This project loads no integration and has no discover source of its own, so discover lists everything instead of answering "${query}".`,+ ),+ );+ }+ const themes = available.flatMap(entry =>+ Array.isArray(entry.themes) ? entry.themes : [],+ );+ blocks.push(+ text(+ [+ 'To add a package, run its install command.',+ ...(themes.length > 0+ ? [+ `Then use a theme it adds: ${run} theme add <theme>, for example ${run} theme add ${themes[0]}`,+ ]+ : []),+ ].join('\n'),+ ),+ );+ } else {+ blocks.push(+ text(+ [+ 'Usage:',+ ` ${run} discover <package> Browse a package and its versions`,+ ` ${run} discover <package>/<item> View one item`,+ ` ${run} discover <search> Search every item and package`,+ ].join('\n'),+ ),+ );+ }emit(...blocks);break;}@@ -378,7 +423,7 @@ export function registerDiscover(program) {const d = result.data;/** @type {import('../formatters/index.mjs').Block[]} */const blocks = [record(d, {omit: ['versions', 'install']})];- if (d.versions) {+ if (d.versions && d.versions.length > 0) {const shown = d.version;const lines = versionLines(d.versions, {shown,@@ -387,12 +432,12 @@ export function registerDiscover(program) {: undefined,latest: d.latest,});- const prereleases = d.versions.filter(v => v.prerelease).length;+ // The shown version is listed even when it is a prerelease.+ const prereleases = d.versions.filter(+ v => v.prerelease && v.version !== shown,+ ).length;blocks.push(- section(- 'Versions',- `${d.versions.length} published, newest first`,- ),+ section('Versions', `${d.versions.length} known, newest first`),);if (lines.length > 0) blocks.push(list(lines));if (prereleases > 0) {@@ -405,10 +450,16 @@ export function registerDiscover(program) {}if (d.install) {blocks.push(- section('Add it'),- code(d.install),- text(- 'Astryx loads an integration on the next command once it is a dependency.',+ ...addBlocks(+ d.install,+ d.themes ?? [],+ addsMoreThanThemes(+ /** @type {Record<string, unknown>} */ (+ /** @type {unknown} */ (d)+ ),+ ),+ run,+ pinNote(d.install, d.version, d.source),),);} else if (d.installedAs) {@@ -420,7 +471,7 @@ export function registerDiscover(program) {}blocks.push(text(- d.installed+ d.installed && d.components.length > 0? `Usage: ${run} discover ${d.name}/<ComponentName>`: `See one item: ${run} discover ${d.name}/<item>`,),@@ -446,13 +497,13 @@ export function registerDiscover(program) {emit(record(d, {omit: ['install']}),...(d.install- ? [- section('Add it'),- code(d.install),- text(- 'Astryx loads an integration on the next command once it is a dependency.',- ),- ]+ ? addBlocks(+ d.install,+ d.kind === 'theme' ? [d.name] : [],+ d.kind !== 'theme',+ run,+ pinNote(d.install, d.version, d.source),+ ): []),text(`Its package: ${run} discover ${d.package}`),);diff --git a/packages/cli/clients/cli/commands/discover.no-source.test.mjs b/packages/cli/clients/cli/commands/discover.no-source.test.mjsindex 530d0c7030..1c92948837 100644--- a/packages/cli/clients/cli/commands/discover.no-source.test.mjs+++ b/packages/cli/clients/cli/commands/discover.no-source.test.mjs@@ -1,75 +1,489 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file `astryx discover` when no discover source is configured and no- * integration provides one.+ * @file `astryx discover` and the official list the CLI carries+ * (spec:AST-051 FR11), in projects with no discover source of their own.*- * In a fresh public app with no integrations, `discover --available` used to- * print "No integrations configured. Add integration package names..." — a- * message that told users to add names they had no way to find. These tests- * pin the honest replacement.+ * A fresh app sees the official Astryx packages it could add, and a declared+ * official theme counts as installed. In a project that loads no integration+ * and has no source of its own, every query still answers with the list (FR1);+ * a project that loads an integration gets package pages and search, where an+ * official theme is added at a pinned version and then with `theme add`.*/import {describe, it, expect, beforeEach, afterEach} from 'vitest';import * as fs from 'node:fs';import * as path from 'node:path';import * as os from 'node:os';+import {fileURLToPath} from 'node:url';import {runCli} from '../../../test-utils/run-cli.mjs';+const CLI_VERSION = JSON.parse(+ fs.readFileSync(+ path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '../../../package.json',+ ),+ 'utf8',+ ),+).version;+let tmpDir;let project;+/** @param {object} [fields] */+function writeProject(fields = {}) {+ fs.writeFileSync(+ path.join(project, 'package.json'),+ JSON.stringify({name: 'my-app', version: '1.0.0', ...fields}),+ );+}++/** @param {string} name @param {string} version */+function install(name, version) {+ const dir = path.join(project, 'node_modules', ...name.split('/'));+ fs.mkdirSync(dir, {recursive: true});+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({name, version}),+ );+}++/** A configured integration, so discover answers queries. */+function addIntegration() {+ const pkg = path.join(project, 'node_modules', '@acme', 'ui');+ fs.mkdirSync(path.join(pkg, 'components'), {recursive: true});+ fs.writeFileSync(+ path.join(pkg, 'package.json'),+ '{"name":"@acme/ui","version":"1.0.0","type":"module"}',+ );+ fs.writeFileSync(+ path.join(pkg, 'astryx.integration.mjs'),+ "export default {components: './components'};\n",+ );+ fs.writeFileSync(+ path.join(pkg, 'components', 'Widget.doc.mjs'),+ 'export const doc = {type: "component", name: "Widget", description: "A widget"};\n',+ );+ fs.writeFileSync(+ path.join(pkg, 'components', 'Widget.tsx'),+ 'export function Widget() { return null; }\n',+ );+ writeProject({type: 'module'});+ fs.writeFileSync(+ path.join(project, 'astryx.config.mjs'),+ "export default {integrations: ['@acme/ui']};\n",+ );+}+beforeEach(() => {tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-discover-nosource-'));project = path.join(tmpDir, 'project');fs.mkdirSync(project, {recursive: true});- fs.writeFileSync(- path.join(project, 'package.json'),- JSON.stringify({name: 'my-app', version: '1.0.0'}),- );+ writeProject();});afterEach(() => {fs.rmSync(tmpDir, {recursive: true, force: true});});-describe('astryx discover --available with no source', () => {- it('explains what discover sources are and where to find packages', async () => {- const {status, stdout} = await runCli(['discover', '--available'], {+describe('astryx discover in a project with nothing of its own', () => {+ it('lists the official packages it could add, each with its add command, and no query hints', async () => {+ const {status, stdout} = await runCli(['discover'], {cwd: project});++ expect(status).toBe(0);+ expect(stdout).toMatch(/^Available$/m);+ expect(stdout).toMatch(/^from Astryx$/m);+ expect(stdout).toMatch(/^name:\s+@astryxdesign\/theme-neutral$/m);+ expect(stdout).toMatch(/^source:\s+Astryx$/m);+ expect(stdout).toMatch(+ new RegExp(+ `^install:\\s+.* @astryxdesign/theme-neutral@${CLI_VERSION}$`,+ 'm',+ ),+ );+ expect(stdout).toContain('To add a package, run its install command.');+ expect(stdout).toMatch(/theme add <theme>, for example .*theme add \w+/);+ // Every query here returns this list, so the list must not suggest one.+ expect(stdout).not.toContain('Usage:');+ expect(stdout).not.toMatch(/discover <(package|search)>/);+ });++ it('keeps the list with meta.configured=false, and reports the official list in meta.sources', async () => {+ const {status, stdout} = await runCli(['discover', '--json'], {+ cwd: project,+ });++ expect(status).toBe(0);+ const result = JSON.parse(stdout);+ expect(result.type).toBe('discover.list');+ expect(result.data).toEqual([]);+ expect(result.meta.configured).toBe(false);+ expect(result.meta.sources).toEqual([+ {+ name: 'Astryx',+ from: '@astryxdesign/cli',+ status: 'fresh',+ complete: true,+ },+ ]);+ expect(result.meta.available.length).toBeGreaterThan(0);+ for (const entry of result.meta.available) {+ expect(entry.source).toBe('Astryx');+ expect(entry.name.startsWith('@astryxdesign/')).toBe(true);+ }+ expect(result.meta.available).toContainEqual(+ expect.objectContaining({+ name: '@astryxdesign/theme-neutral',+ version: CLI_VERSION,+ themes: ['neutral'],+ }),+ );+ });++ it('answers every query with the list, and says why in text', async () => {+ for (const query of ['gothic', '@astryxdesign/theme-gothic', ' ']) {+ const asJson = await runCli(['discover', query, '--json'], {+ cwd: project,+ });+ expect(asJson.status, query).toBe(0);+ expect(JSON.parse(asJson.stdout).type, query).toBe('discover.list');+ }++ const {stdout} = await runCli(['discover', 'gothic'], {cwd: project});+ expect(stdout).toContain(+ 'This project loads no integration and has no discover source of its own, so discover lists everything instead of answering "gothic".',+ );+ expect(stdout).not.toContain('Usage:');+ });++ it('counts a declared official theme as installed, keeps meta.configured, and does not offer it again', async () => {+ writeProject({dependencies: {'@astryxdesign/theme-butter': CLI_VERSION}});+ install('@astryxdesign/theme-butter', '0.7.0');++ const {status, stdout} = await runCli(['discover', '--json'], {+ cwd: project,+ });++ expect(status).toBe(0);+ const {data, meta} = JSON.parse(stdout);+ expect(data).toEqual([+ expect.objectContaining({+ name: '@astryxdesign/theme-butter',+ version: '0.7.0',+ themes: ['butter'],+ latest: CLI_VERSION,+ }),+ ]);+ expect(meta.configured).toBe(false);+ expect(meta.available.map(entry => entry.name)).not.toContain(+ '@astryxdesign/theme-butter',+ );+ });+});++describe('astryx discover and the project’s own package.json', () => {+ it('counts a declared official theme as installed from a subfolder', async () => {+ writeProject({dependencies: {'@astryxdesign/theme-butter': CLI_VERSION}});+ install('@astryxdesign/theme-butter', '0.7.0');+ const src = path.join(project, 'src', 'components');+ fs.mkdirSync(src, {recursive: true});++ const {status, stdout} = await runCli(['discover', '--json'], {cwd: src});++ expect(status).toBe(0);+ const {data, meta} = JSON.parse(stdout);+ expect(data.map(entry => entry.name)).toEqual([+ '@astryxdesign/theme-butter',+ ]);+ expect(meta.available.map(entry => entry.name)).not.toContain(+ '@astryxdesign/theme-butter',+ );+ });++ it('pins the exact Core version a fresh clone declares, before install', async () => {+ writeProject({dependencies: {'@astryxdesign/core': '0.6.8'}});++ const {status, stdout} = await runCli(['discover', '--json'], {+ cwd: project,+ });++ expect(status).toBe(0);+ const neutral = JSON.parse(stdout).meta.available.find(+ entry => entry.name === '@astryxdesign/theme-neutral',+ );+ // The entry shows the latest release and installs the declared Core's.+ expect(neutral.version).toBe(CLI_VERSION);+ expect(neutral.install).toMatch(/ @astryxdesign\/theme-neutral@0\.6\.8$/);+ });++ it('pins the Core range a fresh clone declares, quoted for the shell', async () => {+ writeProject({dependencies: {'@astryxdesign/core': '^0.6.8'}});++ const {status, stdout} = await runCli(['discover', '--json'], {+ cwd: project,+ });++ expect(status).toBe(0);+ const neutral = JSON.parse(stdout).meta.available.find(+ entry => entry.name === '@astryxdesign/theme-neutral',+ );+ expect(neutral.version).toBe(CLI_VERSION);+ expect(neutral.install).toMatch(+ / "@astryxdesign\/theme-neutral@\^0\.6\.8"$/,+ );+ });++ it('neither installs nor offers an official theme the project only peer-depends on', async () => {+ writeProject({+ peerDependencies: {'@astryxdesign/theme-butter': '>=0.7.0'},+ });++ const {stdout} = await runCli(['discover', '--json'], {cwd: project});+ const {data, meta} = JSON.parse(stdout);+ expect(data).toEqual([]);+ expect(meta.available.map(entry => entry.name)).not.toContain(+ '@astryxdesign/theme-butter',+ );+ });++ it('recognizes an official theme installed under an npm alias', async () => {+ writeProject({+ dependencies: {'my-butter': 'npm:@astryxdesign/[email protected]'},+ });+ install('my-butter', '0.7.0');++ const {stdout} = await runCli(['discover', '--json'], {cwd: project});+ expect(JSON.parse(stdout).data).toEqual([+ expect.objectContaining({+ name: '@astryxdesign/theme-butter',+ version: '0.7.0',+ }),+ ]);+ });+});++describe('astryx discover with a source that publishes an official integration under another name', () => {+ beforeEach(() => {+ writeProject({type: 'module'});+ fs.writeFileSync(+ path.join(project, 'astryx.config.mjs'),+ `export default {+ discover: async () => ({+ schemaVersion: 1,+ source: {name: 'Fork catalog', generatedAt: '2026-10-01T00:00:00Z', complete: true},+ packages: [{+ package: '@acme/gothic-fork',+ integration: '@astryxdesign/theme-gothic',+ aliases: [],+ latest: '1.0.0',+ versions: [{version: '1.0.0', publishedAt: null, prerelease: false, status: 'ok'}],+ contributions: [{kind: 'theme', name: 'gothic-fork'}],+ }],+ }),+};+`,+ );+ });++ it('keeps the source’s package in the list and in search', async () => {+ const list = await runCli(['discover', '--available', '--json'], {cwd: project,});+ const names = JSON.parse(list.stdout).meta.available.map(e => e.name);+ expect(names).toContain('@acme/gothic-fork');+ expect(names).not.toContain('@astryxdesign/theme-gothic');+ const search = await runCli(['discover', 'fork', '--json'], {+ cwd: project,+ });+ expect(search.status).toBe(0);+ expect(JSON.parse(search.stdout).data.matches).toEqual(+ expect.arrayContaining([+ expect.objectContaining({package: '@acme/gothic-fork'}),+ ]),+ );+ });+});++describe('astryx discover in a project that loads an integration', () => {+ beforeEach(addIntegration);++ it('lists official packages first among what it could add', async () => {+ const {status, stdout} = await runCli(['discover', '--json'], {+ cwd: project,+ });expect(status).toBe(0);- expect(stdout).toContain('No discover source is configured.');- expect(stdout).toContain('discover sources');- expect(stdout).toContain('npm search @astryxdesign');- expect(stdout).toContain('docs cli/integrations');- // Must not show the old misleading message- expect(stdout).not.toContain('Add integration package names');+ const {data, meta} = JSON.parse(stdout);+ expect(data.map(entry => entry.name)).toEqual(['@acme/ui']);+ expect(meta.available[0].source).toBe('Astryx');});- it('returns an empty list with configured=false in --json', async () => {+ it('adds a theme package at the version shown, then points to theme add', async () => {const {status, stdout} = await runCli(- ['discover', '--available', '--json'],+ ['discover', '@astryxdesign/theme-gothic'],{cwd: project},);expect(status).toBe(0);- const result = JSON.parse(stdout);- expect(result.type).toBe('discover.list');- expect(result.data).toEqual([]);- expect(result.meta).toEqual({configured: false});+ expect(stdout).toMatch(/^installed:\s+false$/m);+ expect(stdout).toContain(`@astryxdesign/theme-gothic@${CLI_VERSION}`);+ expect(stdout).toContain('Then use its theme:');+ expect(stdout).toMatch(/theme add gothic$/m);+ expect(stdout).not.toContain('Astryx loads an integration');});-});-describe('astryx discover with nothing configured', () => {- it('shows the config snippet and a pointer to npm and docs', async () => {- const {status, stdout} = await runCli(['discover'], {cwd: project});+ it("lists the latest release and the project's Core version, pins the Core version, and finds both", async () => {+ for (const [core, latest] of [+ ['0.6.8', CLI_VERSION],+ ['99.0.0', '99.0.0'],+ ]) {+ install('@astryxdesign/core', core);++ const page = await runCli(+ ['discover', '@astryxdesign/theme-gothic', '--json'],+ {cwd: project},+ );+ expect(page.status, core).toBe(0);+ const {data} = JSON.parse(page.stdout);+ expect(data.latest, core).toBe(latest);+ expect(data.version, core).toBe(latest);+ expect(data.versions.map(v => v.version).sort(), core).toEqual(+ [...new Set([CLI_VERSION, core])].sort(),+ );+ expect(data.install, core).toMatch(+ new RegExp(+ ` @astryxdesign/theme-gothic@${core.replaceAll('.', '\\.')}$`,+ ),+ );++ for (const wanted of new Set([core, CLI_VERSION])) {+ const lookup = await runCli(+ ['discover', `@astryxdesign/theme-gothic@${wanted}`, '--json'],+ {cwd: project},+ );+ expect(lookup.status, `${core} ${wanted}`).toBe(0);+ expect(JSON.parse(lookup.stdout).data.version, wanted).toBe(wanted);+ }++ const list = await runCli(['discover', '--json'], {cwd: project});+ expect(+ JSON.parse(list.stdout).meta.available.find(+ entry => entry.name === '@astryxdesign/theme-gothic',+ ).version,+ core,+ ).toBe(latest);+ }+ });++ it('says which version its add command installs when the page shows the latest release', async () => {+ install('@astryxdesign/core', '0.6.8');++ const {status, stdout} = await runCli(+ ['discover', '@astryxdesign/theme-gothic'],+ {cwd: project},+ );expect(status).toBe(0);- expect(stdout).toContain('No integrations configured.');- expect(stdout).toContain("integrations: ['@scope/your-integration']");- expect(stdout).toContain('npm search @astryxdesign');- expect(stdout).toContain('docs cli/integrations');+ expect(stdout).toMatch(+ new RegExp(`^latest:\\s+${CLI_VERSION.replaceAll('.', '\\.')}$`, 'm'),+ );+ expect(stdout).toMatch(/^- 0\.6\.8 {2}date unknown$/m);+ // The verb follows the detected package manager.+ expect(stdout).toMatch(/^\S+ \S+ @astryxdesign\/theme-gothic@0\.6\.8$/m);+ expect(stdout).toContain(+ "This installs 0.6.8, the version that matches this project's Core.",+ );+ });++ it('pins the declared Core range on the page and says so', async () => {+ writeProject({+ type: 'module',+ dependencies: {'@astryxdesign/core': '>=0.6.8 <0.8.0'},+ });++ const {status, stdout} = await runCli(+ ['discover', '@astryxdesign/theme-gothic'],+ {cwd: project},+ );++ expect(status).toBe(0);+ expect(stdout).toMatch(+ /^\S+ \S+ "@astryxdesign\/theme-gothic@>=0\.6\.8 <0\.8\.0"$/m,+ );+ expect(stdout).toContain(+ 'This installs the newest release in >=0.6.8 <0.8.0, the Core range this project declares.',+ );+ });++ it('keeps latest at the newest release for an installed official theme', async () => {+ install('@astryxdesign/core', '0.6.8');+ writeProject({+ type: 'module',+ dependencies: {'@astryxdesign/theme-butter': '0.6.8'},+ });+ install('@astryxdesign/theme-butter', '0.6.8');++ const list = await runCli(['discover', '--json'], {cwd: project});+ expect(+ JSON.parse(list.stdout).data.find(+ entry => entry.name === '@astryxdesign/theme-butter',+ ),+ ).toMatchObject({version: '0.6.8', latest: CLI_VERSION});++ const page = await runCli(['discover', '@astryxdesign/theme-butter'], {+ cwd: project,+ });+ expect(page.stdout).toMatch(+ new RegExp(+ `^- ${CLI_VERSION.replaceAll('.', '\\.')} {2}date unknown {2}latest$`,+ 'm',+ ),+ );+ expect(page.stdout).toMatch(/^- 0\.6\.8 {2}date unknown {2}installed$/m);+ });++ it('keeps the error code for a version or item of an official package it does not show', async () => {+ for (const query of [+ '@astryxdesign/[email protected]',+ '@astryxdesign/theme-gothic@latest',+ '@astryxdesign/theme-gothic/nope',+ ]) {+ const {status, stdout} = await runCli(['discover', query, '--json'], {+ cwd: project,+ });+ expect(status, query).toBe(1);+ expect(JSON.parse(stdout).code, query).toBe('ERR_UNKNOWN_PACKAGE');+ }+ });++ it('points an installed theme’s page at its items, not at components', async () => {+ writeProject({+ type: 'module',+ dependencies: {'@astryxdesign/theme-butter': CLI_VERSION},+ });+ install('@astryxdesign/theme-butter', CLI_VERSION);++ const {stdout} = await runCli(['discover', '@astryxdesign/theme-butter'], {+ cwd: project,+ });+ expect(stdout).toContain('discover @astryxdesign/theme-butter/<item>');+ expect(stdout).not.toContain('<ComponentName>');+ });++ it('finds an official theme by name', async () => {+ const {status, stdout} = await runCli(['discover', 'gothic', '--json'], {+ cwd: project,+ });++ expect(status).toBe(0);+ expect(JSON.parse(stdout).data.matches).toContainEqual(+ expect.objectContaining({+ package: '@astryxdesign/theme-gothic',+ component: 'gothic',+ kind: 'theme',+ installed: false,+ }),+ );});});diff --git a/packages/cli/clients/cli/commands/discover.sources.test.mjs b/packages/cli/clients/cli/commands/discover.sources.test.mjsindex 83c29315b5..62dab145b1 100644--- a/packages/cli/clients/cli/commands/discover.sources.test.mjs+++ b/packages/cli/clients/cli/commands/discover.sources.test.mjs@@ -145,13 +145,20 @@ describe('astryx discover with a discover source', () => {latest: '3.2.0',}),]);- expect(meta.available).toEqual([+ // The official packages come first, then what the project's source adds.+ const official = meta.available.filter(entry => entry.source === 'Astryx');+ expect(official.length).toBeGreaterThan(0);+ expect(meta.available.slice(0, official.length)).toEqual(official);+ // Each entry carries the command that adds it; a source's entry is not+ // pinned, as on its package page.+ expect(meta.available.slice(official.length)).toEqual([{name: '@test/charts',components: ['Chart'],version: '2.0.0',templates: ['pages/Report'],source: 'Test catalog',+ install: expect.stringMatching(/ @test\/charts$/),},{name: '@test/boards',@@ -159,14 +166,26 @@ describe('astryx discover with a discover source', () => {version: '1.0.0',templates: ['pages/DialBoard'],source: 'Test catalog',+ install: expect.stringMatching(/ @test\/boards$/),},]);+ for (const entry of official) {+ expect(entry.install).toMatch(+ new RegExp(` ${entry.name}@${entry.version.replaceAll('.', '\\.')}$`),+ );+ }expect(meta.sources).toEqual([expect.objectContaining({name: 'Test catalog',from: 'astryx.config',status: 'fresh',}),+ {+ name: 'Astryx',+ from: '@astryxdesign/cli',+ status: 'fresh',+ complete: true,+ },]);});diff --git a/packages/cli/clients/cli/commands/json-contract.test.mjs b/packages/cli/clients/cli/commands/json-contract.test.mjsindex 6a09dd9260..22ae37cc36 100644--- a/packages/cli/clients/cli/commands/json-contract.test.mjs+++ b/packages/cli/clients/cli/commands/json-contract.test.mjs@@ -143,7 +143,11 @@ describe('--json contract: supported commands emit valid envelopes', () => {const parsed = parseJson(stdout);expect(parsed.type).toBe('discover.list');expect(parsed.data).toEqual([]);- expect(parsed.meta).toEqual({configured: false});+ expect(parsed.meta.configured).toBe(false);+ // The official list the CLI carries is always a source.+ expect(parsed.meta.sources).toEqual([+ expect.objectContaining({name: 'Astryx', status: 'fresh'}),+ ]);});it('astryx template --json emits a typed envelope', async () => {diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjsindex d7071a167b..18ca6472d6 100644--- a/packages/cli/foundation/response/response-types.doc.mjs+++ b/packages/cli/foundation/response/response-types.doc.mjs@@ -112,7 +112,7 @@ export const doc = {{value: 'discover.list',description:- 'The integrations the project loads (name, category, components, version, a list per other kind they add, and latest when a source knows it); with a discover source, meta.available lists what the project could add and meta.sources reports each source; when empty 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 (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".',},{value: 'discover.detail',diff --git a/scripts/check-cli-official-packages.test.mjs b/scripts/check-cli-official-packages.test.mjsnew file mode 100644index 0000000000..522f81dde5--- /dev/null+++ b/scripts/check-cli-official-packages.test.mjs@@ -0,0 +1,209 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Drift guard for the official package list the CLI carries for+ * `astryx discover` (spec:AST-051 FR11).+ *+ * `scripts/generate-cli-official-packages.mjs` builds the list from the+ * packages the release workflow publishes, with the CLI's own readers. This+ * test pins the committed file to what the generator builds now, and checks+ * the selection rule on a stand-in repository. When a package changes, run+ * `pnpm bundle:cli-official-packages` and commit the regenerated list.+ */++import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import {fileURLToPath} from 'node:url';+import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import {+ buildOfficialList,+ OFFICIAL_LIST_PATH,+ releaseChannel,+ serializeOfficialList,+} from './generate-cli-official-packages.mjs';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const REPO_ROOT = path.resolve(__dirname, '..');++describe('the official package list is in sync with the repository', () => {+ it('matches what the generator builds (run `pnpm bundle:cli-official-packages`)', async () => {+ const committed = fs.readFileSync(+ path.join(REPO_ROOT, OFFICIAL_LIST_PATH),+ 'utf-8',+ );+ expect(committed).toBe(serializeOfficialList(await buildOfficialList()));+ });++ it('releases every listed package with Core, unless it is canary-only', async () => {+ // A package outside Core's version group would show and pin a version it+ // was never released at: a renamed package must move with the group.+ const loose = (await buildOfficialList()).packages+ .filter(p => !p.canaryOnly && !p.releasedWithCore)+ .map(p => p.package);+ expect(loose).toEqual([]);+ });++ it('lists every public theme package and no base package', async () => {+ const names = (await buildOfficialList()).packages.map(p => p.package);+ const themes = fs+ .readdirSync(path.join(REPO_ROOT, 'packages', 'themes'))+ .map(slug =>+ path.join(REPO_ROOT, 'packages', 'themes', slug, 'package.json'),+ )+ .filter(file => fs.existsSync(file))+ .map(file => JSON.parse(fs.readFileSync(file, 'utf-8')))+ .filter(pkg => pkg.private !== true)+ .map(pkg => pkg.name);+ expect(themes.length).toBeGreaterThan(0);+ for (const theme of themes) expect(names).toContain(theme);+ for (const base of [+ '@astryxdesign/core',+ '@astryxdesign/cli',+ '@astryxdesign/build',+ ]) {+ expect(names).not.toContain(base);+ }+ });+});++describe('releaseChannel follows the release workflow publish rule', () => {+ it.each([+ [{name: '@astryxdesign/theme-x'}, 'latest'],+ [{name: '@astryxdesign/theme-x', private: false}, 'latest'],+ [{name: '@astryxdesign/x', private: true}, null],+ [+ {name: '@astryxdesign/x', private: true, astryx: {canaryOnly: true}},+ 'canary',+ ],+ [{name: '@astryxdesign/x', astryx: {canaryOnly: true}}, 'canary'],+ [{name: '@acme/theme-x'}, null],+ [{}, null],+ ])('%o publishes to %s', (pkg, channel) => {+ expect(releaseChannel(pkg)).toBe(channel);+ });+});++describe('buildOfficialList on a stand-in repository', () => {+ /** @type {string} */+ let root;++ /** @param {string} file @param {unknown} value */+ const writeJSON = (file, value) => {+ fs.mkdirSync(path.dirname(file), {recursive: true});+ fs.writeFileSync(file, JSON.stringify(value));+ };++ /**+ * @param {string} slug+ * @param {object} pkg+ * @param {{descriptor?: boolean}} [options]+ */+ const theme = (slug, pkg, {descriptor = true} = {}) => {+ const dir = path.join(root, 'packages', 'themes', slug);+ writeJSON(path.join(dir, 'package.json'), pkg);+ fs.mkdirSync(path.join(dir, 'src'), {recursive: true});+ fs.writeFileSync(+ path.join(dir, 'src', `${slug}Theme.ts`),+ `export const ${slug}Theme = {};\n`,+ );+ if (descriptor) {+ fs.writeFileSync(+ path.join(dir, 'src', `${slug}Theme.doc.mjs`),+ `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\nexport default {type: 'theme', name: '${slug}', displayName: 'Ocean ${slug}', description: 'Blue ${slug}.', maintained: true};\n`,+ );+ }+ };++ beforeEach(() => {+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-official-list-'));+ writeJSON(path.join(root, '.changeset', 'config.json'), {+ fixed: [['@astryxdesign/core', '@astryxdesign/theme-ocean']],+ });+ writeJSON(path.join(root, 'packages', 'core', 'package.json'), {+ name: '@astryxdesign/core',+ description: 'The base.',+ });+ });++ afterEach(() => {+ fs.rmSync(root, {recursive: true, force: true});+ });++ it('keeps published packages that add something, and marks canary-only and Core-released ones', async () => {+ theme('ocean', {name: '@astryxdesign/theme-ocean', description: 'Sea.'});+ theme('lagoon', {+ name: '@astryxdesign/theme-lagoon',+ private: true,+ astryx: {canaryOnly: true},+ });+ theme('probe', {name: '@astryxdesign/theme-probe', private: true});+ theme('reef', {name: '@acme/theme-reef'});++ expect(await buildOfficialList(root)).toEqual({+ packages: [+ {+ package: '@astryxdesign/theme-lagoon',+ canaryOnly: true,+ contributions: [+ {+ kind: 'theme',+ name: 'lagoon',+ title: 'Ocean lagoon',+ summary: 'Blue lagoon.',+ },+ ],+ },+ {+ package: '@astryxdesign/theme-ocean',+ description: 'Sea.',+ releasedWithCore: true,+ contributions: [+ {+ kind: 'theme',+ name: 'ocean',+ title: 'Ocean ocean',+ summary: 'Blue ocean.',+ },+ ],+ },+ ],+ });+ });++ it('refuses a published theme package with no descriptor', async () => {+ theme('bare', {name: '@astryxdesign/theme-bare'}, {descriptor: false});+ await expect(buildOfficialList(root)).rejects.toThrow(+ '@astryxdesign/theme-bare (packages/themes/bare) is published but has no src/bareTheme.ts with a same-stem src/bareTheme.doc.mjs descriptor',+ );+ });++ it('refuses a published theme package whose folder is not its file name', async () => {+ theme('ocean', {name: '@astryxdesign/theme-ocean'});+ fs.renameSync(+ path.join(root, 'packages', 'themes', 'ocean'),+ path.join(root, 'packages', 'themes', 'theme-ocean'),+ );+ await expect(buildOfficialList(root)).rejects.toThrow(+ 'has no src/themeOceanTheme.ts with a same-stem src/themeOceanTheme.doc.mjs descriptor',+ );+ });++ it('refuses a published theme package whose descriptor does not read', async () => {+ theme('ocean', {name: '@astryxdesign/theme-ocean'});+ fs.writeFileSync(+ path.join(+ root,+ 'packages',+ 'themes',+ 'ocean',+ 'src',+ 'oceanTheme.doc.mjs',+ ),+ 'export default {};\n',+ );+ await expect(buildOfficialList(root)).rejects.toThrow(+ 'must declare its public ThemeDoc type',+ );+ });+});diff --git a/scripts/generate-cli-official-packages.mjs b/scripts/generate-cli-official-packages.mjsnew file mode 100644index 0000000000..39151802f4--- /dev/null+++ b/scripts/generate-cli-official-packages.mjs@@ -0,0 +1,282 @@+#!/usr/bin/env node+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Writes the official package list that `astryx discover` reads after+ * every other source (spec:AST-051 FR11 and DEC-5) to+ * `packages/cli/assets/discover/official-packages.json`.+ *+ * A package is official when the release workflow publishes it and it adds at+ * least one item discover lists. The publish rule is the workflow's own: an+ * `@astryxdesign/` name that is not private goes to `latest`, and a+ * `canaryOnly` package goes to `canary` only. What a package adds comes from+ * the CLI's own readers: the integration loader and contribution inventory for+ * an integration, and the theme descriptor reader for a theme package. The list+ * holds no versions: when discover reads it, each entry lists the CLI's own+ * version and the project's installed Core version, and pins the project's+ * Core version, else the Core range it declares, else the latest release. Run+ * from the repo root and commit the result; `--check` exits 1 when the+ * committed list is stale.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {fileURLToPath} from 'node:url';+import {parseTheme} from '../packages/cli/authoring/doctypes/theme/parse.mjs';+import {readThemeDescriptorValue} from '../packages/cli/foundation/discovery/theme-discovery.mjs';+import {collectIdentities} from '../packages/cli/foundation/integrations/contribution-inventory.mjs';+import {loadLocalIntegration} from '../packages/cli/foundation/integrations/integrations.mjs';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const REPO_ROOT = path.resolve(__dirname, '..');++/** Where the list lives, relative to a repository root. */+export const OFFICIAL_LIST_PATH = path.join(+ 'packages',+ 'cli',+ 'assets',+ 'discover',+ 'official-packages.json',+);++/** The folders the release workflow publishes from, in its order. */+const PACKAGE_FOLDERS = ['packages', path.join('packages', 'themes')];++/** The folder whose every published package is a theme package. */+const THEMES_FOLDER = path.join('packages', 'themes');++/**+ * @typedef {object} OfficialContribution+ * @property {import('../packages/cli/authoring/discover/type').DiscoverKind} kind+ * @property {string} name+ * @property {string} [title]+ * @property {string} [summary]+ */++/**+ * @typedef {object} OfficialPackage+ * @property {string} package+ * @property {string} [description]+ * @property {true} [canaryOnly] published only to `canary`+ * @property {true} [releasedWithCore] always released at Core's version+ * @property {OfficialContribution[]} contributions+ */++/** @param {string} file */+const readJSON = file => JSON.parse(fs.readFileSync(file, 'utf-8'));++/** @param {string} slug */+const toIdentifier = slug =>+ slug.replace(/-([a-z])/g, (_, character) => character.toUpperCase());++/**+ * Which dist-tag the release workflow publishes a package to: `latest` (and+ * `canary`) for a public `@astryxdesign/` package, `canary` only for a+ * `canaryOnly` one, and none otherwise.+ * @param {{name?: unknown, private?: unknown, astryx?: {canaryOnly?: unknown}}} pkg+ * @returns {'latest' | 'canary' | null}+ */+export function releaseChannel(pkg) {+ if (typeof pkg.name !== 'string' || !pkg.name.startsWith('@astryxdesign/')) {+ return null;+ }+ const canaryOnly = Boolean(pkg.astryx?.canaryOnly);+ if (!pkg.private && !canaryOnly) return 'latest';+ return canaryOnly ? 'canary' : null;+}++/**+ * The packages released at Core's version: the changeset fixed group that+ * holds `@astryxdesign/core`.+ * @param {string} repoRoot+ * @returns {Set<string>}+ */+function packagesReleasedWithCore(repoRoot) {+ const file = path.join(repoRoot, '.changeset', 'config.json');+ if (!fs.existsSync(file)) return new Set();+ const groups = readJSON(file).fixed ?? [];+ const group = groups.find(+ (/** @type {unknown} */ names) =>+ Array.isArray(names) && names.includes('@astryxdesign/core'),+ );+ return new Set(group ?? []);+}++/**+ * @param {OfficialContribution[]} items+ * @returns {OfficialContribution[]}+ */+function byName(items) {+ return items.sort((a, b) => a.name.localeCompare(b.name, 'en'));+}++/**+ * What an integration package adds, through the same discovery a project+ * that installs it runs.+ * @param {import('../packages/cli/foundation/integrations/integrations.mjs').LoadedIntegration} integration+ * @param {string} name+ * @returns {Promise<OfficialContribution[]>}+ */+async function integrationContributions(integration, name) {+ if (integration.__loadError) {+ throw new Error(+ `${name}: its integration manifest does not load: ${integration.__loadError}`,+ );+ }+ const {identities, errors} = await collectIdentities(integration);+ if (errors.length > 0) {+ throw new Error(+ `${name}: ${errors.map(e => `${e.kind}: ${e.message}`).join('; ')}`,+ );+ }+ return [+ ...byName(identities.components.map(n => ({kind: 'component', name: n}))),+ ...byName(identities.templates.map(t => ({kind: 'template', name: t.id}))),+ ...byName(identities.docs.map(n => ({kind: 'doc', name: n}))),+ ...byName(identities.themes.map(t => ({kind: 'theme', name: t.slug}))),+ ...byName(+ identities.codemods.map(c => ({+ kind: 'codemod',+ name: `${c.version}/${c.id}`,+ })),+ ),+ ].map(item => /** @type {OfficialContribution} */ (item));+}++/**+ * The theme a theme package adds, read by the CLI's theme descriptor reader:+ * `src/<name>Theme.ts` with its same-stem `.doc.mjs` descriptor.+ * @param {string} dir+ * @param {string} name+ * @returns {OfficialContribution[]}+ */+function themeContributions(dir, name) {+ const stem = `${toIdentifier(path.basename(dir))}Theme`;+ const source = path.join(dir, 'src', `${stem}.ts`);+ const descriptor = path.join(dir, 'src', `${stem}.doc.mjs`);+ if (!fs.existsSync(source) || !fs.existsSync(descriptor)) return [];+ const label = `Theme package ${name} descriptor src/${stem}.doc.mjs`;+ const theme = parseTheme(readThemeDescriptorValue(descriptor, label), label);+ return [+ {+ kind: 'theme',+ name: theme.name,+ title: theme.displayName,+ ...(theme.description ? {summary: theme.description} : {}),+ },+ ];+}++/**+ * Build the official list from a repository checkout. Throws when a package the+ * release publishes cannot be read, so a broken package never silently drops+ * out of the list.+ * @param {string} [repoRoot]+ * @returns {Promise<{packages: OfficialPackage[]}>}+ */+export async function buildOfficialList(repoRoot = REPO_ROOT) {+ const withCore = packagesReleasedWithCore(repoRoot);+ /** @type {OfficialPackage[]} */+ const packages = [];+ for (const folder of PACKAGE_FOLDERS) {+ const root = path.join(repoRoot, folder);+ if (!fs.existsSync(root)) continue;+ const dirs = fs+ .readdirSync(root, {withFileTypes: true})+ .filter(entry => entry.isDirectory())+ .map(entry => path.join(root, entry.name))+ .filter(dir => fs.existsSync(path.join(dir, 'package.json')))+ .sort();+ for (const dir of dirs) {+ const pkg = readJSON(path.join(dir, 'package.json'));+ const channel = releaseChannel(pkg);+ if (channel == null) continue;+ const integration = await loadLocalIntegration(dir);+ const contributions = integration+ ? await integrationContributions(integration, pkg.name)+ : themeContributions(dir, pkg.name);+ if (contributions.length === 0) {+ // A published theme package must read back, or it would silently+ // drop out of the list.+ if (folder === THEMES_FOLDER) {+ const stem = `${toIdentifier(path.basename(dir))}Theme`;+ throw new Error(+ `${pkg.name} (${path.relative(repoRoot, dir)}) is published but has no src/${stem}.ts with a same-stem src/${stem}.doc.mjs descriptor, so the official list cannot read its theme.`,+ );+ }+ // Core, the CLI, and the build plugins are the base: they add nothing+ // discover lists.+ continue;+ }+ packages.push({+ package: pkg.name,+ ...(typeof pkg.description === 'string' && pkg.description+ ? {description: pkg.description}+ : {}),+ ...(channel === 'canary' ? {canaryOnly: true} : {}),+ ...(withCore.has(pkg.name) ? {releasedWithCore: true} : {}),+ contributions,+ });+ }+ }+ packages.sort((a, b) => a.package.localeCompare(b.package, 'en'));+ return {packages};+}++/**+ * The file contents for a list.+ * @param {{packages: OfficialPackage[]}} list+ * @returns {string}+ */+export function serializeOfficialList(list) {+ return `${JSON.stringify(list, null, 2)}\n`;+}++async function main() {+ const check = process.argv.includes('--check');+ const out = path.join(REPO_ROOT, OFFICIAL_LIST_PATH);+ let text;+ try {+ text = serializeOfficialList(await buildOfficialList());+ } catch (error) {+ console.error(+ `generate-cli-official-packages: ${error instanceof Error ? error.message : error}`,+ );+ process.exitCode = 1;+ return;+ }+ if (check) {+ const current = fs.existsSync(out) ? fs.readFileSync(out, 'utf-8') : '';+ if (current !== text) {+ console.error(+ `generate-cli-official-packages: ${OFFICIAL_LIST_PATH} is stale. Run \`pnpm bundle:cli-official-packages\` and commit the result.`,+ );+ process.exitCode = 1;+ return;+ }+ console.log(+ `generate-cli-official-packages: ${OFFICIAL_LIST_PATH} is current.`,+ );+ return;+ }+ fs.mkdirSync(path.dirname(out), {recursive: true});+ fs.writeFileSync(out, text);+ const count = JSON.parse(text).packages.length;+ console.log(+ `generate-cli-official-packages: wrote ${count} official packages to ${OFFICIAL_LIST_PATH}`,+ );+}++/** Whether this module is the entry point, however the path to it was spelled. */+function isEntryPoint() {+ try {+ return (+ fs.realpathSync(process.argv[1] ?? '') ===+ fs.realpathSync(fileURLToPath(import.meta.url))+ );+ } catch {+ return false;+ }+}++if (isEntryPoint()) await main();