An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): integration check findings say plainly what is wrong and how to fix it (#7787)
Joeye9694dcf82e1
diff --git a/.changeset/cli-integration-clearer-messages.md b/.changeset/cli-integration-clearer-messages.mdnew file mode 100644index 0000000000..89490b0450--- /dev/null+++ b/.changeset/cli-integration-clearer-messages.md@@ -0,0 +1,14 @@+---+'@astryxdesign/cli': patch+---++[fix] `astryx doctor integration validate`, `astryx integration check` and `astryx integration verify` say more plainly what is wrong in findings they already reported, and how to fix it:++- An empty doc or manifest, or one with no default export, says so and names what it does export, instead of "(root): Invalid input".+- A manifest key one or two letters off a known key asks "did you mean `components`?" before suggesting a newer CLI.+- A theme descriptor named for the built file (`ocean.doc.mjs` beside a built `ocean.js` that lacks the `ocean` export) says it must share its stem with the `defineTheme` source, naming that source when the built module's `Source:` line or the source's `defineTheme` name confirms it.+- A template doc with no source, a theme descriptor with no source, a theme source with no descriptor, and a component whose source is `.jsx` get a `Fix:`.+- A theme source named for its theme (`brand.ts`) beside the module the build writes (`brand.js`) is told to take the `brandTheme` stem.+- `verify` names packed files by their path in the package, not the scratch copy's; says npm pack does not follow a symlinked root instead of asking for a `files` entry; and, when a theme's `defineTheme` name differs from the files its package exports, says a rebuild writes files under the new name.++@josephfarinadiff --git a/packages/cli/api/integration/pack-check.mjs b/packages/cli/api/integration/pack-check.mjsindex 2a0a2ec1a3..ffd82b60e2 100644--- a/packages/cli/api/integration/pack-check.mjs+++ b/packages/cli/api/integration/pack-check.mjs@@ -26,7 +26,11 @@ import {fileURLToPath} from 'node:url';import {spawnSync} from 'node:child_process';import {assertWithin} from '../../foundation/fs/path-safety.mjs';import {resolvePackageDir} from '../../foundation/integrations/integrations.mjs';-import {rootProblem} from '../../foundation/integrations/validate-contributions.mjs';+import {+ literalThemeName,+ rootProblem,+ symlinkedFolder,+} from '../../foundation/integrations/validate-contributions.mjs';import {componentReplacesCliProblem,docsTreeCliProblem,@@ -954,6 +958,10 @@ async function validatePackedThemeExports();}+ // The name the source gives defineTheme, when the file says it: the+ // build names its files after it.+ const builtName = literalThemeName(source, localTheme.exportName);+const declaredOutputs = declaredThemeBuildOutputs(localIntegration,localTheme,@@ -1098,7 +1106,15 @@ async function validatePackedThemeExports(? `Theme "${localTheme.slug}" module is not the module \`${formatCliCommand(`theme build ${sourceRelative}`, localIntegration.__packageDir)}\` writes and does not only wrap it: ${localWrapper.reason}. A module that wraps the built module may only import the theme's own stylesheet and font stylesheet for their side effects and re-export from the built module either everything or only its theme, as ${localTheme.exportName}.`: localWrapper && !localWrapper.ok? `Theme "${localTheme.slug}" module re-exports ${localWrapper.reason}, which does not match ${sourceRelative}. Run \`${formatCliCommand(`theme build ${sourceRelative}`, localIntegration.__packageDir)}\` before packing.`- : `Theme "${localTheme.slug}" ${output.kind} does not match ${sourceRelative}. Run \`${formatCliCommand(`theme build ${sourceRelative}`, localIntegration.__packageDir)}\` before packing.`,+ : (renamedOutputMessage(+ localTheme,+ output.kind,+ output.local,+ source,+ builtName,+ localIntegration.__packageDir,+ ) ??+ `Theme "${localTheme.slug}" ${output.kind} does not match ${sourceRelative}. Run \`${formatCliCommand(`theme build ${sourceRelative}`, localIntegration.__packageDir)}\` before packing.`),),);}@@ -1416,6 +1432,9 @@ export async function integrationPackCheck(options = {}) {);/** @type {string|null} */let scratchBase = null;+ /** @type {string|undefined} the packed copy of the package */+ let extractDir;+ const issuesBeforePack = issues.length;try {// npm pack@@ -1464,11 +1483,16 @@ export async function integrationPackCheck(options = {}) {for (const root of fileInv.roots) {const missing = root.files.filter(f => !packResult.packedPaths.has(f));if (missing.length === root.files.length && root.files.length > 0) {+ const absolute = /** @type {string} */ (loaded[root.kind]);+ const link = symlinkedFolder(absolute, packageDir);issues.push(error('root_not_packed',`Declared ${root.kind} root "${root.path}" has 0 of ${root.files.length} expected ` +- `files in the pack list. Add "${root.path.replace(/^\.\//, '')}" to "files" in package.json.`,+ `files in the pack list. ` ++ (link+ ? `It is reached through the symlink "${path.relative(packageDir, link.path).split(path.sep).join('/')}", and npm pack does not follow a symlinked folder. Fix: replace the link with the folder itself, or point "${root.kind}" at the folder it links to.`+ : `Add "${root.path.replace(/^\.\//, '')}" to "files" in package.json.`),),);} else {@@ -1507,7 +1531,6 @@ export async function integrationPackCheck(options = {}) {}// ── Phase 3: extract + identity comparison ──- let extractDir;try {extractDir = resolvePackageDir(pkgName, scratchBase);} catch (err) {@@ -1629,11 +1652,94 @@ export async function integrationPackCheck(options = {}) {issues,);} finally {+ // The packed copy lives in a scratch folder that is gone once this+ // returns: name its files the way the package does.+ if (extractDir && scratchBase) {+ packageRelative(issues.slice(issuesBeforePack), extractDir, scratchBase);+ }removeTreeBestEffort(tgzTmpDir, 'temporary tarball directory', issues);removeTreeBestEffort(scratchBase, 'scratch consumer', issues);}}+/**+ * When a theme's source names it something other than the file the package+ * exports for it, a rebuild writes new files under that name and leaves the+ * exported one stale forever: say so, with both ways out. Null otherwise.+ * @param {{slug: string}} theme+ * @param {string} kind 'module' or 'stylesheet'+ * @param {string} exported the file the package exports for it+ * @param {string} source the theme's source+ * @param {string | null} builtName the literal defineTheme name, if any+ * @param {string} packageDir+ * @returns {string | null}+ */+function renamedOutputMessage(+ theme,+ kind,+ exported,+ source,+ builtName,+ packageDir,+) {+ if (builtName == null || builtName === theme.slug) return null;+ const extension = kind === 'module' ? '.js' : '.css';+ if (path.basename(exported) === `${builtName}${extension}`) return null;+ const rel = (/** @type {string} */ file) =>+ path.relative(packageDir, file).split(path.sep).join('/');+ const built = rel(+ path.join(path.dirname(source), `${builtName}${extension}`),+ );+ return `Theme "${theme.slug}" ${kind} is ${rel(exported)}, but ${path.basename(source)} calls defineTheme with name: '${builtName}', so \`${formatCliCommand(`theme build ${rel(source)}`, packageDir)}\` writes ${built} instead and rebuilding never updates ${path.basename(exported)}. Fix: point the package export that serves it at ${built} after building, or set name: '${theme.slug}' in ${path.basename(source)} and rebuild.`;+}++/**+ * Rewrite the scratch copy's absolute paths in each issue's message: a file+ * of the packed package as its path in the package, and any other path in the+ * scratch consumer (such as the module that resolved an import) as that+ * consumer. Both folders are gone once verify returns.+ * @param {Issue[]} issues+ * @param {string} packedDir the packed package inside the scratch consumer+ * @param {string} consumerDir the scratch consumer+ */+function packageRelative(issues, packedDir, consumerDir) {+ /** @param {string} dir */+ const spellings = dir => {+ const out = [dir];+ try {+ const real = fs.realpathSync(dir);+ if (real !== dir) out.push(real);+ } catch {+ // Already removed: the plain path is all there is.+ }+ return out;+ };+ /** @param {string} text */+ const escape = text => text.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');+ const packed = spellings(packedDir);+ const consumer = spellings(consumerDir);+ for (const issue of issues) {+ if (typeof issue.message !== 'string') continue;+ let message = issue.message;+ for (const prefix of packed) {+ message = message+ .split(`${prefix}${path.sep}`)+ .join('')+ .replace(+ new RegExp(`${escape(prefix)}(?![\\w-]|\\.\\w)`, 'gu'),+ 'the package root',+ );+ }+ for (const prefix of consumer) {+ message = message.replace(+ new RegExp(`${escape(prefix)}[^\\s"'\`]*`, 'gu'),+ 'a consumer project',+ );+ }+ issue.message = message;+ }+}+/*** Assemble the receipt.* @param {string} namediff --git a/packages/cli/api/integration/pack-check.test.mjs b/packages/cli/api/integration/pack-check.test.mjsindex 39e3e39d08..9daad9f1a6 100644--- a/packages/cli/api/integration/pack-check.test.mjs+++ b/packages/cli/api/integration/pack-check.test.mjs@@ -580,6 +580,24 @@ describe('a theme module that loads its own styles', () => {expect(cli.status, cli.stderr).toBe(0);});+ it('says a rebuild cannot fix exports that name the theme after its folder once its source renames it', async () => {+ writePackage({+ files: ['astryx.integration.mjs', 'themes'],+ themeExports: true,+ });+ fs.writeFileSync(+ path.join(tmpDir, 'themes', 'ocean', 'oceanTheme.ts'),+ "import {defineTheme} from '@astryxdesign/core/theme';\n\nexport const oceanTheme = defineTheme({name: 'sea'});\n",+ );++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.issues.map(issue => issue.message)).toEqual([+ `Theme "ocean" module is themes/ocean/ocean.js, but oceanTheme.ts calls defineTheme with name: 'sea', so \`${formatCliCommand('theme build themes/ocean/oceanTheme.ts', tmpDir)}\` writes themes/ocean/sea.js instead and rebuilding never updates ocean.js. Fix: point the package export that serves it at themes/ocean/sea.js after building, or set name: 'ocean' in oceanTheme.ts and rebuild.`,+ `Theme "ocean" stylesheet is themes/ocean/ocean.css, but oceanTheme.ts calls defineTheme with name: 'sea', so \`${formatCliCommand('theme build themes/ocean/oceanTheme.ts', tmpDir)}\` writes themes/ocean/sea.css instead and rebuilding never updates ocean.css. Fix: point the package export that serves it at themes/ocean/sea.css after building, or set name: 'ocean' in oceanTheme.ts and rebuild.`,+ ]);+ });+it('compares a partial export set with the module named after the theme', async () => {writeRenamedOcean();setThemeExports({'./themes/ocean': './themes/ocean/deep-sea.js'});@@ -1919,6 +1937,57 @@ describe('integrationPackCheck', () => {expect(sourceWarnings[0].message).toContain('stray.tsx');});+ it('says npm pack skips a symlinked root instead of asking for a "files" entry', async () => {+ writePackage({+ manifest:+ "export default {themes: './themes', components: './components'};\n",+ });+ const real = path.join(tmpDir, 'real-components');+ fs.mkdirSync(real, {recursive: true});+ fs.writeFileSync(+ path.join(real, 'Card.doc.mjs'),+ "export default {type: 'component', name: 'Card', displayName: 'Card', usage: {description: 'Card.'}, props: []};\n",+ );+ fs.writeFileSync(+ path.join(real, 'Card.tsx'),+ 'export function Card() { return null; }\n',+ );+ fs.symlinkSync('real-components', path.join(tmpDir, 'components'));++ const result = await integrationPackCheck({cwd: tmpDir});+ const codes = result.data.issues.map(issue => issue.code);+ expect(codes).toContain('symlinked_root');+ const notPacked = result.data.issues.find(+ issue => issue.code === 'root_not_packed',+ );+ expect(notPacked?.message).toBe(+ 'Declared components root "components" has 0 of 2 expected files in the pack list. It is reached through the symlink "components", and npm pack does not follow a symlinked folder. Fix: replace the link with the folder itself, or point "components" at the folder it links to.',+ );+ });++ it('names packed files by their path in the package, never the scratch copy', async () => {+ writePackage({+ manifest:+ "export default {themes: './themes', docs: './docs/a.doc.mjs'};\n",+ });+ fs.mkdirSync(path.join(tmpDir, 'docs'), {recursive: true});+ fs.writeFileSync(path.join(tmpDir, 'docs', 'a.doc.mjs'), '');++ const result = await integrationPackCheck({cwd: tmpDir});+ const messages = result.data.issues.map(issue => issue.message);+ expect(messages.join('\n')).not.toContain(+ path.join(tmpDir, '.astryx-pack-check-'),+ );+ expect(messages).toContain(+ 'Packed: Declared docs root is a file, not a folder: docs/a.doc.mjs. Fix: point "docs" in the manifest at the folder that holds them.',+ );+ // The root's own issue covers it: no empty-root error, no raw errno.+ const codes = result.data.issues.map(issue => issue.code);+ expect(codes).not.toContain('empty_contribution_root');+ expect(codes).not.toContain('local_discovery_failed');+ expect(codes).not.toContain('packed_discovery_failed');+ });+it('fails on a package.json npm cannot pack, which validate only warns about', async () => {writePackage({files: ['astryx.integration.mjs', 'themes']});const packageFile = path.join(tmpDir, 'package.json');diff --git a/packages/cli/api/integration/validate-integration-gaps.test.mjs b/packages/cli/api/integration/validate-integration-gaps.test.mjsindex 95b7d4a44b..fc1922d938 100644--- a/packages/cli/api/integration/validate-integration-gaps.test.mjs+++ b/packages/cli/api/integration/validate-integration-gaps.test.mjs@@ -28,6 +28,7 @@ import {summarizeCheck,} from './check/check.mjs';import {componentDocNamesCheck} from '../../foundation/integrations/validate-contributions.mjs';+import {formatCliCommand} from '../../foundation/env/package-manager.mjs';let tmpDir;let copies = 0;@@ -1023,6 +1024,219 @@ describe('component doc files', () => {});expect(await issuesOf(fixed)).toEqual([]);});++ it('names a .jsx source beside a component doc and says to rename it', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './components'}),+ 'components/AcmeWidget.doc.mjs': componentDoc('AcmeWidget'),+ 'components/AcmeWidget.jsx': componentSource('AcmeWidget'),+ });++ const message = only(await issuesOf(dir), 'invalid_component');+ expect(message).toBe(+ 'Component "AcmeWidget" is missing its same-stem source file AcmeWidget.tsx: found AcmeWidget.jsx, but a component source must be a .tsx file. Fix: rename AcmeWidget.jsx to AcmeWidget.tsx (and point its package export at the new file).',+ );++ const fixed = follow(dir, {+ move: [['components/AcmeWidget.jsx', 'components/AcmeWidget.tsx']],+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it('says what an empty doc and a doc with no default export are missing', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './components'}),+ 'components/Empty.doc.mjs': '',+ 'components/Empty.tsx': componentSource('Empty'),+ 'components/Named.doc.mjs': componentDoc('Named').replace(+ 'export default',+ 'export const doc =',+ ),+ 'components/Named.tsx': componentSource('Named'),+ });++ const messages = (await issuesOf(dir)).map(issue => issue.message);+ const fix =+ 'Fix: export the doc object as the default export: `export default {type: ..., name: ..., ...}`.';+ expect(messages).toEqual([+ `Component "Empty" has invalid metadata: ${path.join(dir, 'components', 'Empty.doc.mjs')} is empty, so it documents nothing. ${fix}`,+ `Component "Named" has invalid metadata: ${path.join(dir, 'components', 'Named.doc.mjs')} has no default export or \`docs\` export (it exports \`doc\`), so it documents nothing. ${fix}`,+ ]);+ expect(messages.join('\n')).not.toContain('Invalid input');+ });+});++describe('template and theme pairing', () => {+ it('gives a template doc with no source a fix', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({templates: './templates'}),+ 'templates/account-card.doc.mjs': templateDoc('Account card'),+ });++ const message = only(await issuesOf(dir), 'invalid_template');+ expect(message).toBe(+ 'Template "account-card" is missing its same-stem source file account-card.tsx. Fix: add account-card.tsx beside account-card.doc.mjs, with the template as its default export.',+ );+ const fixed = follow(dir, {+ write: {'templates/account-card.tsx': templateSource},+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ const themeDoc = `${THEME_TYPE}export default {type: 'theme', name: 'ocean', displayName: 'Ocean', description: 'A theme.', maintained: true};\n`;+ const themeSource =+ "import {defineTheme} from '@astryxdesign/core/theme';\nexport const oceanTheme = defineTheme({name: 'ocean'});\n";++ it('gives a theme descriptor with no source a fix', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({themes: './themes'}),+ 'themes/ocean/oceanTheme.doc.mjs': themeDoc,+ });++ expect(only(await issuesOf(dir), 'invalid_theme')).toBe(+ 'Theme "ocean" for @acme/kit must contain exactly one same-stem source for oceanTheme.doc.mjs; found 0. Fix: add oceanTheme.ts beside oceanTheme.doc.mjs, exporting `oceanTheme` from defineTheme.',+ );+ });++ it('gives a theme source with no descriptor a fix', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({themes: './themes'}),+ 'themes/ocean/oceanTheme.ts': themeSource,+ });++ const message = only(await issuesOf(dir), 'invalid_theme');+ expect(message).toBe(+ `Theme "ocean" for @acme/kit must contain exactly one same-stem .doc.mjs descriptor; found 0 beside "oceanTheme.ts". Fix: add oceanTheme.doc.mjs beside it with type: 'theme' and name: 'ocean'; \`${formatCliCommand('docs authoring theme-doc', path.join(dir, 'themes', 'ocean'))}\` lists its fields.`,+ );+ const fixed = follow(dir, {+ write: {'themes/ocean/oceanTheme.doc.mjs': themeDoc},+ });+ expect(+ (await issuesOf(fixed)).filter(issue => issue.code === 'invalid_theme'),+ ).toEqual([]);+ });++ it('says to rename a source named for its theme when the build writes beside it, and the rename clears it', async () => {+ const brandDoc = `${THEME_TYPE}export default {type: 'theme', name: 'brand', displayName: 'Brand', description: 'A theme.', maintained: true};\n`;+ const dir = writePackage({+ [MANIFEST]: manifest({themes: './themes'}),+ 'themes/brand/brand.doc.mjs': brandDoc,+ 'themes/brand/brand.ts':+ "import {defineTheme} from '@astryxdesign/core/theme';\nexport const brand = defineTheme({name: 'brand'});\n",+ 'themes/brand/brand.js':+ "/**\n * @generated by `astryx theme build` — do not edit manually.\n */\nimport './brand.css';\nexport const brandTheme = {};\n",+ 'themes/brand/brand.css': '.astryx-theme-brand {}\n',+ });++ expect(only(await issuesOf(dir), 'invalid_theme')).toBe(+ `Theme "brand" for @acme/kit must contain exactly one same-stem source for brand.doc.mjs; found 2: "brand.js", "brand.ts". Fix: "brand.js" is the module \`${formatCliCommand('theme build', path.join(dir, 'themes', 'brand'))}\` writes, which takes the theme's name; rename brand.ts to brandTheme.ts and brand.doc.mjs to brandTheme.doc.mjs, export \`brandTheme\` from it, and build again.`,+ );++ const fixed = follow(dir, {+ remove: ['themes/brand/brand.ts', 'themes/brand/brand.doc.mjs'],+ write: {+ 'themes/brand/brandTheme.ts':+ "import {defineTheme} from '@astryxdesign/core/theme';\nexport const brandTheme = defineTheme({name: 'brand'});\n",+ 'themes/brand/brandTheme.doc.mjs': brandDoc,+ },+ });+ expect(+ (await issuesOf(fixed)).filter(issue => issue.code === 'invalid_theme'),+ ).toEqual([]);+ });++ const builtOcean = (/** @type {string} */ extra) =>+ `/**\n * @generated by \`astryx theme build\` — do not edit manually.\n${extra} */\nimport './ocean.css';\nexport const oceanTheme = {};\n`;++ it("names the theme's source when its defineTheme gives the theme's name, for a descriptor named for the built module", async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({themes: './themes'}),+ 'themes/ocean/ocean.doc.mjs': themeDoc,+ 'themes/ocean/oceanTheme.ts': themeSource,+ 'themes/ocean/ocean.js': builtOcean(''),+ 'themes/ocean/ocean.css': '.astryx-theme-ocean {}\n',+ });++ const message = only(await issuesOf(dir), 'invalid_theme');+ expect(message).toContain(+ 'shares its stem with the built module "ocean.js", which does not export "ocean": a descriptor must share its stem with the source that calls defineTheme. The theme\'s source is "oceanTheme.ts". Fix: rename ocean.doc.mjs to oceanTheme.doc.mjs.',+ );+ const fixed = follow(dir, {+ move: [['themes/ocean/ocean.doc.mjs', 'themes/ocean/oceanTheme.doc.mjs']],+ });+ expect(+ (await issuesOf(fixed)).filter(issue => issue.code === 'invalid_theme'),+ ).toEqual([]);+ });++ it("names the source the built module's Source: line gives, over a <name>Theme helper", async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({themes: './themes'}),+ 'themes/ocean/ocean.doc.mjs': themeDoc,+ 'themes/ocean/seaTheme.ts': themeSource.replace('oceanTheme', 'seaTheme'),+ 'themes/ocean/baseTheme.ts':+ "import {defineTheme} from '@astryxdesign/core/theme';\nexport const baseTheme = defineTheme({name: 'base'});\n",+ 'themes/ocean/ocean.js': builtOcean(+ ' * Source: themes/ocean/seaTheme.ts\n',+ ),+ 'themes/ocean/ocean.css': '.astryx-theme-ocean {}\n',+ });++ expect(only(await issuesOf(dir), 'invalid_theme')).toContain(+ 'The theme\'s source is "seaTheme.ts". Fix: rename ocean.doc.mjs to seaTheme.doc.mjs.',+ );+ });++ it('never names a lone <name>Theme helper as the source: the message stays generic', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({themes: './themes'}),+ 'themes/ocean/ocean.doc.mjs': themeDoc,+ 'themes/ocean/oceanTheme.ts':+ "import {defineTheme} from '@astryxdesign/core/theme';\nexport const oceanTheme = defineTheme({name: 'base'});\n",+ 'themes/ocean/ocean.js': builtOcean(''),+ 'themes/ocean/ocean.css': '.astryx-theme-ocean {}\n',+ });++ const message = only(await issuesOf(dir), 'invalid_theme');+ expect(message).toContain(+ 'shares its stem with the built module "ocean.js", which does not export "ocean": a descriptor must share its stem with the source that calls defineTheme. Fix: rename ocean.doc.mjs to share its stem with the theme\'s source (the module that calls defineTheme, such as oceanTheme.ts).',+ );+ expect(message).not.toContain("The theme's source is");+ });++ it('accepts a descriptor named for a built module that exports its stem, as 0.7.2 does', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({themes: './themes'}),+ 'themes/ocean/ocean.doc.mjs': themeDoc,+ 'themes/ocean/oceanTheme.ts': themeSource,+ 'themes/ocean/ocean.js': builtOcean('').replace(+ 'export const oceanTheme = {};',+ 'export const oceanTheme = {};\nexport const ocean = oceanTheme;',+ ),+ 'themes/ocean/ocean.css': '.astryx-theme-ocean {}\n',+ });++ expect(+ (await issuesOf(dir)).filter(issue => issue.code === 'invalid_theme'),+ ).toEqual([]);+ });+});++describe('a theme folder with a helper', () => {+ it('reads a descriptor beside its own defineTheme source, with a <name>Theme helper beside them', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({themes: './themes'}),+ 'themes/brand/brand.doc.mjs': `${THEME_TYPE}export default {type: 'theme', name: 'brand', displayName: 'Brand', description: 'A theme.', maintained: true};\n`,+ 'themes/brand/brand.ts':+ "import {defineTheme} from '@astryxdesign/core/theme';\nimport {baseTheme} from './baseTheme';\nexport const brand = defineTheme({name: 'brand', extends: baseTheme});\n",+ 'themes/brand/baseTheme.ts':+ "import {defineTheme} from '@astryxdesign/core/theme';\nexport const baseTheme = defineTheme({name: 'base'});\n",+ });++ expect(+ (await issuesOf(dir)).filter(issue => issue.code === 'invalid_theme'),+ ).toEqual([]);+ });});describe('a hidden doc beside a source whose name differs only in case', () => {@@ -1404,6 +1618,84 @@ describe('package.json', () => {});});+describe('the manifest', () => {+ it('asks about a key one letter from a known one before blaming the CLI version', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({component: './components'}),+ });++ const message = only(await issuesOf(dir), 'unknown_manifest_key');+ expect(message).toBe(+ 'This CLI does not know the manifest key "component", so it is ignored. Did you mean `components`? Fix: rename "component" to "components" in astryx.integration.mjs. If it is a key from a newer Astryx CLI instead, upgrading @astryxdesign/cli picks it up.',+ );+ });++ it('says to remove a near-miss key when the manifest already sets the key it suggests', async () => {+ const dir = writePackage({+ [MANIFEST]: manifest({components: './components', component: './x'}),+ 'components/AcmeWidget.doc.mjs': componentDoc('AcmeWidget'),+ 'components/AcmeWidget.tsx': componentSource('AcmeWidget'),+ });++ expect(only(await issuesOf(dir), 'unknown_manifest_key')).toBe(+ 'This CLI does not know the manifest key "component", so it is ignored. Did you mean `components`? Fix: remove "component" from astryx.integration.mjs; it already sets "components". If it is a key from a newer Astryx CLI instead, upgrading @astryxdesign/cli picks it up.',+ );+ const fixed = follow(dir, {+ write: {[MANIFEST]: manifest({components: './components'})},+ });+ expect(await issuesOf(fixed)).toEqual([]);+ });++ it.each([+ [+ 'alone, though the package name gives a provider ID',+ {providerID: '@acme/kit', docs: './docs'},+ 'Fix: rename "providerID" to "providerId" in astryx.integration.mjs.',+ ],+ [+ 'beside the key it suggests',+ {providerID: '@acme/kit', providerId: '@acme/kit', docs: './docs'},+ 'Fix: remove "providerID" from astryx.integration.mjs; it already sets "providerId".',+ ],+ ])(+ 'reads the keys the manifest declares: providerID %s',+ async (_label, keys, fix) => {+ const dir = writePackage({+ [MANIFEST]: manifest(keys),+ 'docs/a.doc.mjs': topic('a'),+ });++ expect(only(await issuesOf(dir), 'unknown_manifest_key')).toContain(fix);+ },+ );++ it('keeps the newer-CLI explanation for a key that is no near miss', async () => {+ const dir = writePackage({[MANIFEST]: manifest({playgrounds: './x'})});++ expect(only(await issuesOf(dir), 'unknown_manifest_key')).toContain(+ 'published against a newer Astryx CLI',+ );+ });++ it('says a manifest has no default export, and what it exports', async () => {+ const dir = writePackage({+ [MANIFEST]: "export const integration = {docs: './docs'};\n",+ });++ expect(only(await issuesOf(dir), 'invalid_manifest')).toBe(+ "Integration manifest (astryx.integration.mjs) has no default export (it exports `integration`). Fix: export the manifest object as the default export: `export default {components: './components'}`, naming the roots the package has.",+ );+ });++ it('says a manifest is empty', async () => {+ const dir = writePackage({[MANIFEST]: ''});++ expect(only(await issuesOf(dir), 'invalid_manifest')).toMatch(+ /^Integration manifest \(astryx\.integration\.mjs\) is empty\. Fix: /u,+ );+ });+});+describe('unreadable files and theme names', () => {const asRoot = process.getuid?.() === 0;diff --git a/packages/cli/api/integration/validate-integration.mjs b/packages/cli/api/integration/validate-integration.mjsindex e931abc12d..3a0ac6f949 100644--- a/packages/cli/api/integration/validate-integration.mjs+++ b/packages/cli/api/integration/validate-integration.mjs@@ -328,12 +328,14 @@ async function validateAtPackageDir(let manifest;/** @type {string[]} */let unknownKeys;+ /** @type {string[]} */+ let declaredKeys;/** @type {string | undefined} */let agentDocsError;/** @type {string | undefined} */let cliCommandError;try {- ({manifest, unknownKeys, agentDocsError, cliCommandError} =+ ({manifest, unknownKeys, declaredKeys, agentDocsError, cliCommandError} =await loadManifest(manifestFile,`Integration manifest (${path.basename(manifestFile)})`,@@ -400,6 +402,7 @@ async function validateAtPackageDir(__cliCommandError: cliCommandError,__agentDocsError: agentDocsError,__unknownKeys: unknownKeys,+ __declaredKeys: declaredKeys,__spec: identity.name,__declaredProviderId: manifest.providerId,__packageDir: packageDir,diff --git a/packages/cli/api/integration/validate-integration.type.mjs b/packages/cli/api/integration/validate-integration.type.mjsindex 6d83cdf223..b3ae9e6531 100644--- a/packages/cli/api/integration/validate-integration.type.mjs+++ b/packages/cli/api/integration/validate-integration.type.mjs@@ -18,6 +18,7 @@* @property {string} [codemods]* @property {string} [docs]* @property {string} [issuesUrl]+ * @property {string[]} [__declaredKeys]* @property {string[]} [__unknownKeys]* @property {string} __spec* @property {string} __packageDirdiff --git a/packages/cli/foundation/config/project.test.mjs b/packages/cli/foundation/config/project.test.mjsindex 72067f66a9..227a7ec4b0 100644--- a/packages/cli/foundation/config/project.test.mjs+++ b/packages/cli/foundation/config/project.test.mjs@@ -291,6 +291,32 @@ describe('Project.load', () => {});});+describe('Project.issues and a near-miss manifest key', () => {+ it.each([+ [+ 'alone, while the loaded integration fills providerId from the package name',+ {providerID: '@acme/widgets'},+ 'Fix: rename "providerID" to "providerId" in astryx.integration.mjs.',+ ],+ [+ 'beside the key it suggests',+ {providerID: '@acme/widgets', providerId: '@acme/widgets'},+ 'Fix: remove "providerID" from astryx.integration.mjs; it already sets "providerId".',+ ],+ ])(+ 'reads the keys the manifest declares: providerID %s',+ async (_label, unknownKeys, fix) => {+ scaffold({unknownKeys});+ const project = await Project.load(tmpDir);+ const keys = (await project.issues()).filter(+ issue => issue.code === 'unknown_manifest_key',+ );+ expect(keys).toHaveLength(1);+ expect(keys[0].message).toContain(fix);+ },+ );+});+describe('Project.load and the cliCommand an integration declares', () => {it('records it, so the picker prints commands with it', async () => {scaffold({cliCommand: 'acme astryx'});diff --git a/packages/cli/foundation/discovery/template-adapter.mjs b/packages/cli/foundation/discovery/template-adapter.mjsindex 72b1899b3f..e8116ccbbb 100644--- a/packages/cli/foundation/discovery/template-adapter.mjs+++ b/packages/cli/foundation/discovery/template-adapter.mjs@@ -1192,6 +1192,23 @@ function reportSamePackageReplacements(pkg, autolinked, templates, errors) {}}+/**+ * The fix for a template doc with no same-stem `.tsx`: rename a same-stem+ * source written in another extension, or add the `.tsx`.+ * @param {string} docPath+ * @param {string} sourcePath the `.tsx` it needs+ */+function missingTemplateSourceFix(docPath, sourcePath) {+ const source = path.basename(sourcePath);+ const stem = source.slice(0, -'.tsx'.length);+ const other = ['.jsx', '.js', '.ts', '.mjs']+ .map(extension => `${stem}${extension}`)+ .find(file => fs.existsSync(path.join(path.dirname(sourcePath), file)));+ return other+ ? `Found ${other}, but a template source must be a .tsx file. Fix: rename ${other} to ${source}.`+ : `Fix: add ${source} beside ${path.basename(docPath)}, with the template as its default export.`;+}+/*** Discover the templates contributed by a SINGLE integration. Same per-template* rules as {@link discoverIntegrationTemplates} (same-stem source required,@@ -1225,7 +1242,7 @@ export async function discoverIntegrationTemplatesForOne(integration) {errors.push({package: pkgLabel,template: id,- message: `Template "${id}" is missing its same-stem source file ${path.basename(sourcePath)}.`,+ message: `Template "${id}" is missing its same-stem source file ${path.basename(sourcePath)}. ${missingTemplateSourceFix(docPath, sourcePath)}`,});// A replacement this unusable template declares still counts, so its// target fails closed instead of going to a sibling.diff --git a/packages/cli/foundation/discovery/theme-discovery.mjs b/packages/cli/foundation/discovery/theme-discovery.mjsindex 6f517d4bdb..24afc0cd65 100644--- a/packages/cli/foundation/discovery/theme-discovery.mjs+++ b/packages/cli/foundation/discovery/theme-discovery.mjs@@ -22,6 +22,7 @@ import * as path from 'node:path';import {lowerDoc} from '../doc-compiler/compile.mjs';import {packageSource} from '../doc-compiler/source.mjs';import {CLI_ROOT} from '../fs/paths.mjs';+import {formatCliCommand} from '../env/package-manager.mjs';import {LOCAL_THEME_ROOT} from '../config/theme-state.mjs';import {assertWithin, PathSafetyError} from '../fs/path-safety.mjs';@@ -958,6 +959,126 @@ function declaresThemeDoc(ast, exportDefault) {});}+/**+ * Whether a file is the module `astryx theme build` writes rather than a+ * theme source: plain JavaScript that carries the build's generated header+ * and never calls defineTheme.+ * @param {string} file+ */+function isBuiltThemeModule(file) {+ if (!/\.m?js$/u.test(file)) return false;+ let text;+ try {+ text = fs.readFileSync(file, 'utf8');+ } catch {+ return false;+ }+ return (+ /@generated by `astryx theme build`/u.test(text) &&+ !/\bdefineTheme\b/u.test(text)+ );+}++/**+ * The fix when a descriptor's stem names both a theme source and the module+ * `astryx theme build` writes beside it (`brand.ts` and its built `brand.js`):+ * the build names its output after the theme, so the source and descriptor+ * take the `<name>Theme` stem instead. Null when no built module is among+ * the matches, or the stem already ends in `Theme`.+ * @param {string} sourceDir+ * @param {string[]} sources same-stem module file names+ * @param {string} doc the descriptor's file name+ * @param {string} exportName the descriptor's stem+ * @returns {string | null}+ */+function builtThemeSourceFix(sourceDir, sources, doc, exportName) {+ if (exportName.endsWith('Theme')) return null;+ const built = sources.filter(file =>+ isBuiltThemeModule(path.join(sourceDir, file)),+ );+ const source = sources.filter(file => !built.includes(file));+ if (built.length === 0 || source.length !== 1) return null;+ const extension = source[0].slice(exportName.length);+ const stem = `${exportName}Theme`;+ return `Fix: ${built.map(file => `"${file}"`).join(', ')} is the module \`${formatCliCommand('theme build', sourceDir)}\` writes, which takes the theme's name; rename ${source[0]} to ${stem}${extension} and ${doc} to ${stem}${THEME_DOC_SUFFIX}, export \`${stem}\` from it, and build again.`;+}++/**+ * Why a descriptor pairs with the built module and the built module lacks+ * the export the descriptor's stem names (`ocean.doc.mjs` beside a built+ * `ocean.js` that exports `oceanTheme`): the descriptor is named for the+ * build's output, not the theme's source. The source is named only when the+ * built module's `Source:` header, or a source whose defineTheme gives the+ * theme's name, confirms it; otherwise the message stays generic. Null when+ * the entry is not a built module.+ * @param {string} label the descriptor, as messages name it+ * @param {string} sourceDir+ * @param {string} entry the file the descriptor pairs with+ * @param {string} exportName the descriptor's stem+ * @param {string} doc the descriptor's file name+ * @param {string} slug the theme's name+ * @param {string[]} files the theme folder's files+ * @returns {string | null}+ */+function builtModuleDescriptorMessage(+ label,+ sourceDir,+ entry,+ exportName,+ doc,+ slug,+ files,+) {+ if (!isBuiltThemeModule(path.join(sourceDir, entry))) return null;+ const source = confirmedThemeSource(sourceDir, entry, slug, files);+ const head = `${label} shares its stem with the built module "${entry}", which does not export "${exportName}": a descriptor must share its stem with the source that calls defineTheme.`;+ if (source == null) {+ return `${head} Fix: rename ${doc} to share its stem with the theme's source (the module that calls defineTheme, such as ${exportName}Theme.ts).`;+ }+ const stem = source.replace(/\.[^.]+$/u, '');+ return `${head} The theme's source is "${source}". Fix: rename ${doc} to ${stem}${THEME_DOC_SUFFIX}.`;+}++/**+ * The theme's source, when something confirms it: the file the built+ * module's `Source:` header names, if it is in the folder, else the one+ * module in the folder whose defineTheme gives the theme's name as a+ * literal. Null otherwise: a `<name>Theme` file alone may be a helper.+ * @param {string} sourceDir+ * @param {string} built the built module's file name+ * @param {string} slug+ * @param {string[]} files+ * @returns {string | null}+ */+function confirmedThemeSource(sourceDir, built, slug, files) {+ const own = files.filter(+ file =>+ !file.includes('/') &&+ file !== built &&+ THEME_MODULE_EXTENSIONS.some(extension => file.endsWith(extension)),+ );+ /** @param {string} file */+ const read = file => {+ try {+ return fs.readFileSync(path.join(sourceDir, file), 'utf8');+ } catch {+ return '';+ }+ };+ const header = /^\s*\*?\s*Source:\s*(\S+)\s*$/mu.exec(read(built));+ if (header) {+ const named = path.posix.basename(header[1].replace(/\\/gu, '/'));+ if (own.includes(named)) return named;+ }+ const quoted = slug.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');+ const naming = new RegExp(+ `\\bdefineTheme\\s*\\(\\s*\\{[^}]*\\bname\\s*:\\s*['"\`]${quoted}['"\`]`,+ 'u',+ );+ const matches = own.filter(file => naming.test(read(file)));+ return matches.length === 1 ? matches[0] : null;+}+/** A module named for the theme it exports, such as `oceanTheme.ts`. */const THEME_SOURCE_RE = /^[$A-Z_a-z][$\w]*Theme\.(?:mjs|js|mts|ts|tsx|jsx)$/u;@@ -1240,8 +1361,17 @@ export function discoverThemeDirectory(: evidence.includes('/')? `; "${evidence}" is in a subfolder`: ` beside "${evidence}"`;+ const themeDoc = formatCliCommand('docs authoring theme-doc', sourceDir);+ const fix =+ docs.length > 1+ ? `Fix: keep the one descriptor that shares its stem with the theme's source and delete the rest.`+ : evidence.includes('/')+ ? `Fix: move "${evidence}" up into ${slug}/, beside where its descriptor goes.`+ : THEME_SOURCE_RE.test(evidence)+ ? `Fix: add ${evidence.replace(/\.[^.]+$/u, '')}${THEME_DOC_SUFFIX} beside it with type: 'theme' and name: '${slug}'; \`${themeDoc}\` lists its fields.`+ : `Fix: add a descriptor that shares its stem with the theme's source, with type: 'theme' and name: '${slug}'; \`${themeDoc}\` lists its fields.`;throw new Error(- `${theme} must contain exactly one same-stem .doc.mjs descriptor; found ${docs.length}${detail}.`,+ `${theme} must contain exactly one same-stem .doc.mjs descriptor; found ${docs.length}${detail}. ${fix}`,);}const nested = descriptors.find(file => file.includes('/'));@@ -1267,8 +1397,13 @@ export function discoverThemeDirectory(extension => `${exportName}${extension}`,).filter(file => listing.files.includes(file));if (sources.length !== 1) {+ const fix =+ sources.length > 1+ ? (builtThemeSourceFix(sourceDir, sources, docs[0], exportName) ??+ `Fix: keep one of them; the theme's source is a single module.`)+ : `Fix: add ${exportName}.ts beside ${docs[0]}, exporting \`${exportName}\` from defineTheme.`;throw new Error(- `${theme} must contain exactly one same-stem source for ${docs[0]}; found ${sources.length}${sources.length > 1 ? `: ${quoted(sources)}` : ''}.`,+ `${theme} must contain exactly one same-stem source for ${docs[0]}; found ${sources.length}${sources.length > 1 ? `: ${quoted(sources)}` : ''}. ${fix}`,);}@@ -1314,7 +1449,16 @@ export function discoverThemeDirectory()) {throw new ThemeRuntimeExportError(- `Theme "${slug}" for ${owner} entry "${entry}" does not export "${exportName}".`,+ builtModuleDescriptorMessage(+ label,+ sourceDir,+ entry,+ exportName,+ docs[0],+ slug,+ listing.files,+ ) ??+ `Theme "${slug}" for ${owner} entry "${entry}" does not export "${exportName}".`,);}} catch (error) {diff --git a/packages/cli/foundation/doc-compiler/read.mjs b/packages/cli/foundation/doc-compiler/read.mjsindex 9ce6065d88..bbeba72275 100644--- a/packages/cli/foundation/doc-compiler/read.mjs+++ b/packages/cli/foundation/doc-compiler/read.mjs@@ -173,8 +173,23 @@ export async function readDocView(file, options) {);if (result.loadFailed) throw result.loadFailure;if (result.missing) {- if (strict)+ if (strict) {+ // A doc that exports nothing its reader takes (an empty file, or one+ // with other exports) is said plainly, with what it does export and+ // the fix; the schema would only say "(root): Invalid input".+ const exported =+ options.exports ??+ /** @type {Record<string, readonly string[]>} */ (DOC_EXPORTS)[+ options.root+ ] ??+ [];+ const problem =+ result.missingValue === undefined+ ? await missingDocProblem(file, options, exported)+ : null;+ if (problem) throw new Error(`${options.label ?? file} ${problem}`);parserFor(options.root)(result.missingValue, options.label ?? file);+ }return result.missingValue;}if (strict && result.failed) throw result.failure;@@ -182,6 +197,49 @@ export async function readDocView(file, options) {return result.view;}+/**+ * Why a doc file exports no doc, with the fix: it is empty, or it exports+ * other names than the ones its reader takes. Null when neither explains it.+ * @param {string} file+ * @param {ReadOptions} options+ * @param {readonly string[]} exported the export names the reader takes+ * @returns {Promise<string | null>}+ */+async function missingDocProblem(file, options, exported) {+ // A theme descriptor is read statically, never imported.+ if (options.root === 'themes') return null;+ const fix =+ 'Fix: export the doc object as the default export: `export default {type: ..., name: ..., ...}`.';+ let text;+ try {+ text = fs.readFileSync(file, 'utf8');+ } catch {+ return null;+ }+ const code = text+ .replace(/^\uFEFF/u, '')+ .replace(/\/\*[\s\S]*?\*\//gu, '')+ .replace(/(^|[^:])\/\/.*$/gmu, '$1')+ .trim();+ if (code === '') return `is empty, so it documents nothing. ${fix}`;+ /** @type {string[]} */+ let names;+ try {+ const mod = await LOADERS[options.loader ?? 'user'](file);+ names = Object.keys(mod ?? {}).filter(name => name !== 'default');+ } catch {+ return null;+ }+ const takes = exported.map(name =>+ name === 'default' ? 'default export' : `\`${name}\` export`,+ );+ const found =+ names.length > 0+ ? ` (it exports ${names.map(name => `\`${name}\``).join(', ')})`+ : ' (it exports nothing)';+ return `has no ${takes.join(' or ')}${found}, so it documents nothing. ${fix}`;+}+/*** Load one file as its root reads it: the doc its module exports and, for a* component or hook, the translation it exports for `lang`.diff --git a/packages/cli/foundation/doc-compiler/read.test.mjs b/packages/cli/foundation/doc-compiler/read.test.mjsindex 8a5a7bd1a7..6d671b2b10 100644--- a/packages/cli/foundation/doc-compiler/read.test.mjs+++ b/packages/cli/foundation/doc-compiler/read.test.mjs@@ -109,10 +109,19 @@ describe('readDocView', () => {}});- it("reads a file with no doc as undefined, or as its parser's error when checked", async () => {+ it('reads a file with no doc as undefined, or, checked, says what it exports instead', async () => {const file = write('Empty.doc.mjs', 'export const unrelated = 1;\n');await expect(loadDocs(file)).resolves.toBeUndefined();- await expect(loadComponentDoc(file)).rejects.toThrow(`${file} is invalid`);+ await expect(loadComponentDoc(file)).rejects.toThrow(+ `${file} has no default export or \`docs\` export (it exports \`unrelated\`), so it documents nothing. Fix: export the doc object as the default export`,+ );+ });++ it('says a checked doc file is empty', async () => {+ const file = write('Blank.doc.mjs', '// nothing yet\n');+ await expect(loadComponentDoc(file)).rejects.toThrow(+ `${file} is empty, so it documents nothing.`,+ );});it('applies the translation a module exports for the reading language', async () => {diff --git a/packages/cli/foundation/integrations/integrations.mjs b/packages/cli/foundation/integrations/integrations.mjsindex 88f81a018f..e4057f71f4 100644--- a/packages/cli/foundation/integrations/integrations.mjs+++ b/packages/cli/foundation/integrations/integrations.mjs@@ -73,6 +73,8 @@ import {resolveProviders} from './provider-resolution.mjs';* set on a package whose provider ID an earlier-loaded package already* claims; it contributes nothing and is reported as a `duplicate_provider`* warning+ * @property {string[]} [__declaredKeys] the keys the manifest object itself+ * declares, before any is filled in (providerId from the package name)* @property {string[]} [__unknownKeys] manifest keys this CLI does not know —* surfaced as a warning; the rest of the manifest still contributes* @property {boolean} [__autolinked] loaded because the project declares the@@ -215,7 +217,7 @@ function parseDiscoverSourceExport(value, label) {* @param {string} file absolute manifest path* @param {string} [label] used in error messages* @param {{fresh?: boolean}} [options]- * @returns {Promise<{manifest: import('../../authoring/integration/type').AstryxIntegration, unknownKeys: string[], debug?: import('../../authoring/debug/type').DebugEventHandler, gapReport?: import('../../authoring/gap-report/type').GapReportHandler, gapReportError?: string, discover?: import('../../authoring/discover/type').DiscoverSource, discoverError?: string, agentDocsError?: string, cliCommandError?: string}>}+ * @returns {Promise<{manifest: import('../../authoring/integration/type').AstryxIntegration, unknownKeys: string[], declaredKeys: string[], debug?: import('../../authoring/debug/type').DebugEventHandler, gapReport?: import('../../authoring/gap-report/type').GapReportHandler, gapReportError?: string, discover?: import('../../authoring/discover/type').DiscoverSource, discoverError?: string, agentDocsError?: string, cliCommandError?: string}>}*/export async function loadManifest(file,@@ -224,6 +226,7 @@ export async function loadManifest() {const mod = await importUserModule(file, {fresh});const raw = mod?.default;+ if (raw === undefined) throw new Error(noDefaultExportMessage(file, label, mod));const baseManifest = parseIntegrationBase(raw, label);const gapReport = parseGapReportHandlerExport(mod?.gapReport, label);const discover = parseDiscoverSourceExport(mod?.discover, label);@@ -276,6 +279,8 @@ export async function loadManifest(...(cliCommand == null ? {} : {cliCommand}),},unknownKeys: unknownIntegrationKeys(raw),+ declaredKeys:+ raw != null && typeof raw === 'object' ? Object.keys(raw) : [],debug:typeof mod?.debug === 'function'? /** @type {import('../../authoring/debug/type').DebugEventHandler} */ (@@ -291,6 +296,30 @@ export async function loadManifest(};}+/**+ * Why a manifest has no default export, said plainly instead of as a schema+ * failure on `undefined`: the file is empty, or it exports other names.+ * @param {string} file+ * @param {string} label+ * @param {Record<string, unknown> | undefined} mod+ */+function noDefaultExportMessage(file, label, mod) {+ const fix = `Fix: export the manifest object as the default export: \`export default {components: './components'}\`, naming the roots the package has.`;+ let text = '';+ try {+ text = fs.readFileSync(file, 'utf8');+ } catch {+ // Unreadable now: say only what is missing.+ }+ const names = Object.keys(mod ?? {}).filter(name => name !== 'default');+ if (text.trim() === '') return `${label} is empty. ${fix}`;+ const found =+ names.length > 0+ ? ` (it exports ${names.map(name => `\`${name}\``).join(', ')})`+ : '';+ return `${label} has no default export${found}. ${fix}`;+}+/*** Load and validate a manifest module's default export against the integration* schema. Throws if the default export is missing or invalid. Exposed for@@ -398,6 +427,8 @@ export async function loadLocalIntegration(packageDir, {fresh = false} = {}) {let manifest;/** @type {string[]} */let unknownKeys;+ /** @type {string[]} */+ let declaredKeys;/** @type {import('../../authoring/debug/type').DebugEventHandler | undefined} */let debugHandler;/** @type {import('../../authoring/gap-report/type').GapReportHandler | undefined} */@@ -416,6 +447,7 @@ export async function loadLocalIntegration(packageDir, {fresh = false} = {}) {({manifest,unknownKeys,+ declaredKeys,debug: debugHandler,gapReport: gapReportHandler,gapReportError,@@ -464,6 +496,7 @@ export async function loadLocalIntegration(packageDir, {fresh = false} = {}) {__cliCommandError: cliCommandError,__agentDocsError: agentDocsError,__unknownKeys: unknownKeys,+ __declaredKeys: declaredKeys,__debug: debugHandler,__gapReport: gapReportHandler,__gapReportError: gapReportError,@@ -514,6 +547,8 @@ export async function loadIntegrations(let manifest;/** @type {string[]} */let unknownKeys;+ /** @type {string[]} */+ let declaredKeys;/** @type {import('../../authoring/debug/type').DebugEventHandler | undefined} */let debugHandler;/** @type {import('../../authoring/gap-report/type').GapReportHandler | undefined} */@@ -532,6 +567,7 @@ export async function loadIntegrations(({manifest,unknownKeys,+ declaredKeys,debug: debugHandler,gapReport: gapReportHandler,gapReportError,@@ -587,6 +623,7 @@ export async function loadIntegrations(__cliCommandError: cliCommandError,__agentDocsError: agentDocsError,__unknownKeys: unknownKeys,+ __declaredKeys: declaredKeys,__debug: debugHandler,__gapReport: gapReportHandler,__gapReportError: gapReportError,diff --git a/packages/cli/foundation/integrations/validate-contributions.mjs b/packages/cli/foundation/integrations/validate-contributions.mjsindex ba98ee6fa8..d81dbc7b0a 100644--- a/packages/cli/foundation/integrations/validate-contributions.mjs+++ b/packages/cli/foundation/integrations/validate-contributions.mjs@@ -26,6 +26,7 @@ import * as path from 'node:path';import {parse as parseModule} from '@babel/parser';import {isValidSemver} from '../env/semver.mjs';import {findProjectCoreDir} from '../fs/paths.mjs';+import {KNOWN_INTEGRATION_KEYS} from '../../authoring/integration/schema.mjs';import {contributionFiles,findSourceOnlyCandidates,@@ -127,11 +128,36 @@ export function isListedIssue(issue) {function checkUnknownKeys(integration, issues) {const keys = integration.__unknownKeys ?? [];if (keys.length === 0) return;+ // A key one edit away from a known one is almost always a typo: say so+ // first, since "a newer CLI" sends the author to upgrade for nothing.+ const typos = keys+ .map(key => ({key, known: nearestKnownKey(key)}))+ .filter(each => each.known != null);+ for (const {key, known} of typos) {+ // The manifest object already declares the key it is a near miss of:+ // renaming would give it twice, so the stray key goes. Read from what+ // the manifest says, not the loaded integration, which fills some keys+ // in (providerId from the package name).+ const alreadySet = (integration.__declaredKeys ?? []).includes(+ /** @type {string} */ (known),+ );+ const fix = alreadySet+ ? `Fix: remove "${key}" from ${manifestName(integration)}; it already sets "${known}".`+ : `Fix: rename "${key}" to "${known}" in ${manifestName(integration)}.`;+ issues.push(+ issueWarning(+ 'unknown_manifest_key',+ `This CLI does not know the manifest key "${key}", so it is ignored. Did you mean \`${known}\`? ${fix} If it is a key from a newer Astryx CLI instead, upgrading @astryxdesign/cli picks it up.`,+ ),+ );+ }+ const rest = keys.filter(key => !typos.some(each => each.key === key));+ if (rest.length === 0) return;issues.push(issueWarning('unknown_manifest_key',- `This CLI does not know the manifest ${keys.length === 1 ? 'key' : 'keys'} ` +- `${keys.map(key => `"${key}"`).join(', ')}, so ${keys.length === 1 ? 'it is' : 'they are'} ` ++ `This CLI does not know the manifest ${rest.length === 1 ? 'key' : 'keys'} ` ++ `${rest.map(key => `"${key}"`).join(', ')}, so ${rest.length === 1 ? 'it is' : 'they are'} ` +`ignored — everything else in the manifest still applies. This usually ` +`means the integration was published against a newer Astryx CLI than ` +`this project resolves; upgrading @astryxdesign/cli picks it up.`,@@ -146,6 +172,53 @@ function manifestName(integration) {: 'the integration manifest';}+/**+ * The known manifest key `key` is a near miss of: a different letter case, or+ * at most two letters added, dropped or changed (`component`, `doc`,+ * `tempaltes`). Null when no known key is that close, or two are.+ * @param {string} key+ * @returns {string | null}+ */+export function nearestKnownKey(key) {+ const lower = key.toLowerCase();+ const limit = lower.length <= 4 ? 1 : 2;+ /** @type {string[]} */+ const close = [];+ for (const known of KNOWN_INTEGRATION_KEYS) {+ const distance = editDistance(lower, known.toLowerCase());+ if (distance <= limit) close.push(known);+ }+ return close.length === 1 ? close[0] : null;+}++/**+ * Levenshtein distance, with a swap of two neighbours counted as one edit.+ * @param {string} a+ * @param {string} b+ */+function editDistance(a, b) {+ /** @type {number[][]} */+ const d = Array.from({length: a.length + 1}, (_, i) =>+ Array.from({length: b.length + 1}, (_, j) =>+ i === 0 ? j : j === 0 ? i : 0,+ ),+ );+ for (let i = 1; i <= a.length; i++) {+ for (let j = 1; j <= b.length; j++) {+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;+ d[i][j] = Math.min(+ d[i - 1][j] + 1,+ d[i][j - 1] + 1,+ d[i - 1][j - 1] + cost,+ );+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);+ }+ }+ }+ return d[a.length][b.length];+}+/*** Why a declared root cannot be read as a folder, or null when it can.* A missing root keeps its own issue; a root that is a file or that the@@ -1005,13 +1078,20 @@ async function checkComponents(integration, issues) {const docName = docPath? path.basename(docPath): `${record.name}.doc.mjs`;+ let message = error.message;let fix = `Fix: add ${record.name}.tsx beside ${docName}.`;const stamp = docPath ? readContributionStamp(docPath, false) : null;if (stamp && stamp.type !== 'component' && integration.__packageDir) {context ??= createFixContext(integration.__packageDir, integration);fix = notAComponentFix(context, docPath, stamp);+ } else {+ const other = docPath ? otherSourceFor(docPath) : null;+ if (other) {+ message = `${message.replace(/\.$/u, '')}: found ${other}, but a component source must be a .tsx file.`;+ fix = `Fix: rename ${other} to ${record.name}.tsx (and point its package export at the new file).`;+ }}- issues.push(issueError('invalid_component', `${error.message} ${fix}`));+ issues.push(issueError('invalid_component', `${message} ${fix}`));}/** @type {Set<string>} sources a case-only rename is reported for */const reportedSources = new Set();@@ -1104,6 +1184,21 @@ function docStemOf(file) {return suffix ? file.slice(0, -suffix.length) : file;}+/**+ * A same-stem source discovery does not read: `.jsx`, `.js`, `.ts` or `.mjs`.+ * @param {string} docPath+ * @returns {string | null} its file name+ */+function otherSourceFor(docPath) {+ const stem = docStemOf(path.basename(docPath));+ const dir = path.dirname(docPath);+ return (+ ['.jsx', '.js', '.ts', '.mjs']+ .map(extension => `${stem}${extension}`)+ .find(file => fs.existsSync(path.join(dir, file))) ?? null+ );+}+/*** The component docs under a root, read from the real directory listings:* those beside a source whose name differs only in letter case (which an@@ -1370,6 +1465,80 @@ async function checkThemes(integration, issues) {}}+/**+ * The `name` a theme source passes to defineTheme for its exported theme,+ * when the file says it as a string literal: `export const oceanTheme =+ * defineTheme({name: 'ocean', ...})`. Null whenever only running the module+ * could tell (a variable, a factory, a spread after the name, `extends`+ * alone), so nothing is judged that a build would decide.+ * @param {string} file+ * @param {string} exportName+ * @returns {string | null}+ */+export function literalThemeName(file, exportName) {+ let ast;+ try {+ ast = parseModule(fs.readFileSync(file, 'utf8'), {+ sourceType: 'module',+ plugins: ['typescript', 'jsx'],+ errorRecovery: true,+ });+ } catch {+ return null;+ }+ /** @type {any} */+ let init = null;+ for (const node of ast.program.body) {+ const declaration =+ node.type === 'ExportNamedDeclaration' ? node.declaration : node;+ if (declaration?.type !== 'VariableDeclaration') continue;+ for (const declarator of declaration.declarations) {+ if (+ declarator.id.type === 'Identifier' &&+ declarator.id.name === exportName+ ) {+ init = declarator.init;+ }+ }+ }+ while (+ init?.type === 'TSAsExpression' ||+ init?.type === 'TSSatisfiesExpression'+ ) {+ init = init.expression;+ }+ if (init?.type !== 'CallExpression') return null;+ const callee =+ init.callee.type === 'Identifier'+ ? init.callee.name+ : init.callee.type === 'MemberExpression' &&+ init.callee.property.type === 'Identifier'+ ? init.callee.property.name+ : null;+ if (callee !== 'defineTheme') return null;+ const [config] = init.arguments;+ if (config?.type !== 'ObjectExpression') return null;+ /** @type {string | null} */+ let name = null;+ for (const property of config.properties) {+ if (property.type === 'SpreadElement') {+ name = null;+ continue;+ }+ if (property.type !== 'ObjectProperty' || property.computed) continue;+ const key =+ property.key.type === 'Identifier'+ ? property.key.name+ : property.key.type === 'StringLiteral'+ ? property.key.value+ : null;+ if (key !== 'name') continue;+ name =+ property.value.type === 'StringLiteral' ? property.value.value : null;+ }+ return name;+}+/*** A warning for each contribution file a reader reads (the docs and sources* `integration verify` expects in the tarball) that the user running astryx