An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): make .mjs sources fully strict-typecheckable via checkJs + JSDoc (#4283)
Joey4cc4d7a5683d
diff --git a/.changeset/strict-typecheck-cli.md b/.changeset/strict-typecheck-cli.mdnew file mode 100644index 0000000000..028249bb3c--- /dev/null+++ b/.changeset/strict-typecheck-cli.md@@ -0,0 +1,10 @@+---+'@astryxdesign/cli': patch+'@astryxdesign/core': patch+---++[fix] Make the CLI's `.mjs` sources fully strict-typecheckable (checkJs + JSDoc)++Annotated the entire CLI package so `tsconfig.strict.json` (full `strict` `checkJs` over `src`, `bin`, `scripts`, `docs`, and the emitted `templates`) reports zero errors — down from 1717. Fixes are JSDoc-only: no runtime logic changed, `.mjs` stays `.mjs`. Strict checking also surfaced and corrected several type-contract drifts: the `upgrade.run` response type (declared a `depsUpdated` field the command never emits, and omitted the real `integrations`/`filesChanged`/`transformsApplied`/`errors`), registered the emitted `theme.list`/`theme.add`/`layout.*` response types in the `--json` envelope union, and added `category?` to `ReferenceSection` in core's docs types (reference docs already emit it).++@josephfarinadiff --git a/packages/cli/bin/astryx.mjs b/packages/cli/bin/astryx.mjsindex cf850e1694..871de1abbf 100755--- a/packages/cli/bin/astryx.mjs+++ b/packages/cli/bin/astryx.mjs@@ -26,6 +26,7 @@ import {realpathSync} from 'node:fs';import {dirname, join} from 'node:path';const binDir = dirname(realpathSync(fileURLToPath(import.meta.url)));+/** @param {string} rel */const importSrc = rel =>import(pathToFileURL(join(binDir, '..', 'src', rel)).href);@@ -72,6 +73,7 @@ function inJsonMode() {return isJsonMode() || process.argv.slice(2).includes('--json');}+/** @param {unknown} err */function handleFatal(err) {// CommanderError (parse errors, --help, unknown command) routes// through the JSON shim so that a --json consumer always gets adiff --git a/packages/cli/scripts/postinstall.mjs b/packages/cli/scripts/postinstall.mjsindex 4ecfcc7a37..3eb936b622 100644--- a/packages/cli/scripts/postinstall.mjs+++ b/packages/cli/scripts/postinstall.mjs@@ -24,11 +24,11 @@ const HERE = fileURLToPath(import.meta.url);* Pure decision: should the postinstall print the setup nudge? Split out so the* matrix is unit-testable without an actual npm install.*- * @param {object} opts- * @param {string} opts.scriptPath - Absolute path of this script (location tells+ * @param {object} [opts]+ * @param {string} [opts.scriptPath] - Absolute path of this script (location tells* us dependency vs monorepo vs npx-cache).* @param {string} [opts.npmCommand] - process.env.npm_command ('install', 'exec', …).- * @param {boolean} opts.isSetUp - Whether the project already ran init.+ * @param {boolean} [opts.isSetUp] - Whether the project already ran init.* @returns {boolean}*/export function shouldNudge({scriptPath, npmCommand, isSetUp} = {}) {diff --git a/packages/cli/src/api/blog.mjs b/packages/cli/src/api/blog.mjsindex 78aa9e7778..f9c47e85da 100644--- a/packages/cli/src/api/blog.mjs+++ b/packages/cli/src/api/blog.mjs@@ -20,6 +20,10 @@ const MAX_BYTES = 5 * 1024 * 1024; // 5 MB — a blog feed is never larger.const FEED_URL = new URL('/rss.xml', SITE_URL).toString();+/**+ * @param {string} url+ * @returns {Promise<string>}+ */async function fetchText(url) {const controller = new AbortController();const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);@@ -31,7 +35,12 @@ async function fetchText(url) {});} catch (e) {clearTimeout(timer);- const reason = e.name === 'AbortError' ? 'timed out' : e.message;+ const reason =+ e instanceof Error+ ? e.name === 'AbortError'+ ? 'timed out'+ : e.message+ : String(e);throw new AstryxError(`Could not reach ${url}: ${reason}`,[],@@ -61,6 +70,7 @@ async function fetchText(url) {* Defense in depth: a post's plaintext URL comes from feed content. Require it* to live on the canonical origin so even a tampered feed can't redirect the* CLI to another host.+ * @param {string} target*/function assertCanonicalOrigin(target) {let targetOrigin;@@ -82,6 +92,10 @@ function assertCanonicalOrigin(target) {}}+/**+ * @param {string} value+ * @returns {string}+ */function unescapeXml(value) {return value.replace(/</g, '<')@@ -91,12 +105,23 @@ function unescapeXml(value) {.replace(/&/g, '&');}+/**+ * @param {string} item+ * @param {string} name+ * @returns {string}+ */function tag(item, name) {const m = item.match(new RegExp(`<${name}[^>]*>([\\s\\S]*?)</${name}>`));return m ? unescapeXml(m[1].trim()) : '';}+/**+ * @param {string} item+ * @param {string} name+ * @returns {string[]}+ */function tagAll(item, name) {+ /** @type {string[]} */const out = [];const re = new RegExp(`<${name}[^>]*>([\\s\\S]*?)</${name}>`, 'g');let m;@@ -104,7 +129,11 @@ function tagAll(item, name) {return out;}-/** Extract the plaintext alternate href from an <item>. */+/**+ * Extract the plaintext alternate href from an <item>.+ * @param {string} item+ * @returns {string | null}+ */function textHref(item) {// Match the atom:link alternate regardless of attribute order/quoting; then// confirm it's the text/plain alternate before trusting the href.@@ -121,7 +150,11 @@ function textHref(item) {return null;}-/** Derive a slug from a post link (last path segment). */+/**+ * Derive a slug from a post link (last path segment).+ * @param {string} link+ * @returns {string}+ */function slugFromLink(link) {try {const path = new URL(link).pathname.replace(/\/$/, '');@@ -131,6 +164,9 @@ function slugFromLink(link) {}}+/**+ * @param {string} xml+ */function parseFeed(xml) {const items = [];const re = /<item>([\s\S]*?)<\/item>/g;diff --git a/packages/cli/src/api/component.mjs b/packages/cli/src/api/component.mjsindex e570c1b93b..9cf2b9b641 100644--- a/packages/cli/src/api/component.mjs+++ b/packages/cli/src/api/component.mjs@@ -29,17 +29,39 @@ import {searchComponents} from '../lib/string-utils.mjs';import {AstryxError} from './error.mjs';import {findShowcase, findRelatedBlocks} from './template.mjs';+/**+ * A loaded component doc. `loadDocs` returns the authored `.doc.mjs` shape,+ * which is either a single-component or multi-component doc; this loose view+ * captures the fields the API reads across both forms.+ * @typedef {object} LoadedComponentDoc+ * @property {string} [name]+ * @property {string} [description]+ * @property {any[]} [props]+ * @property {any[]} [components]+ * @property {{description?: string}} [usage]+ * @property {any} [theming]+ */++/**+ * Options object for `loadDocs`, matching its declared parameter shape (used+ * as a cast target so `lang` (which the API may hold as `string|null`) type+ * checks against `loadDocs`'s `lang?: string`).+ * @typedef {{zh?: boolean, dense?: boolean, lang?: string}} LoadDocsOpts+ */+/*** Load the configured integrations for `cwd`, swallowing any config errors so* component discovery never hard-fails on a malformed/absent integration. An* empty list means "core only".* @param {string} cwd- * @returns {Promise<Array<{name: string, components?: string, issuesUrl?: string}>>}+ * @returns {Promise<import('../lib/integrations.mjs').LoadedIntegration[]>}*/async function loadIntegrationsSafely(cwd) {try {const project = await Project.load(cwd);- return project.loadedIntegrations;+ return /** @type {import('../lib/integrations.mjs').LoadedIntegration[]} */ (+ project.loadedIntegrations+ );} catch {return [];}@@ -47,7 +69,7 @@ async function loadIntegrationsSafely(cwd) {/*** Resolve a loaded integration by package name.- * @param {Array<{name: string}>} loadedIntegrations+ * @param {import('../lib/integrations.mjs').LoadedIntegration[]} loadedIntegrations* @param {string} packageName*/function findLoadedIntegration(loadedIntegrations, packageName) {@@ -133,7 +155,7 @@ export async function component(name, options = {}) {const readme = findComponentReadme(coreDir, comp);if (readme && readme.endsWith('.doc.mjs')) {try {- const docs = await loadDocs(readme, {zh, lang});+ const docs = /** @type {LoadedComponentDoc} */ (await loadDocs(readme, /** @type {LoadDocsOpts} */ ({zh, lang})));entries.push({name: comp, description: docs.usage?.description || docs.description || '', import: resolveImportPath(coreDir, comp)});} catch {entries.push({name: comp, description: '', import: resolveImportPath(coreDir, comp)});@@ -151,7 +173,7 @@ export async function component(name, options = {}) {const readme = findComponentReadme(coreDir, comp);if (readme && readme.endsWith('.doc.mjs')) {try {- entries.push(await loadDocs(readme, {zh, lang, dense}));+ entries.push(await loadDocs(readme, /** @type {LoadDocsOpts} */ ({zh, lang, dense})));} catch {entries.push({name: `XDS${comp}`, description: ''});}@@ -181,7 +203,7 @@ export async function component(name, options = {}) {const readme = findComponentReadme(coreDir, comp);if (readme && readme.endsWith('.doc.mjs')) {try {- const docs = await loadDocs(readme, {zh, lang});+ const docs = /** @type {LoadedComponentDoc} */ (await loadDocs(readme, /** @type {LoadDocsOpts} */ ({zh, lang})));result[cat].push({name: comp, description: docs.usage?.description || docs.description || '', import: resolveImportPath(coreDir, comp)});} catch {result[cat].push({name: comp, description: '', import: resolveImportPath(coreDir, comp)});@@ -203,7 +225,7 @@ export async function component(name, options = {}) {const readme = findComponentReadme(coreDir, comp);if (readme && readme.endsWith('.doc.mjs')) {try {- result[cat].push(await loadDocs(readme, {zh, lang, dense}));+ result[cat].push(await loadDocs(readme, /** @type {LoadDocsOpts} */ ({zh, lang, dense})));} catch {result[cat].push({name: `XDS${comp}`, description: ''});}@@ -238,7 +260,7 @@ export async function component(name, options = {}) {const groupLabel = rec.group ?? integration.name;const key = `${groupLabel} (${integration.name})`;if (!byGroup.has(key)) byGroup.set(key, []);- byGroup.get(key).push({name: rec.name, package: integration.name});+ byGroup.get(key)?.push({name: rec.name, package: integration.name});}for (const [key, members] of byGroup) {members.sort((a, b) => a.name.localeCompare(b.name));@@ -334,14 +356,14 @@ export async function component(name, options = {}) {* `package`, the resolved `import` specifier, and `sourceAvailable` (whether* a swizzleable source file exists for the owner). Existing doc fields* (name, usage, props, …) are preserved.- * @param {object} docs+ * @param {LoadedComponentDoc} docs* @param {{package: string, sourcePath: string|null}} owner* @param {string} componentName*/function withOwnership(docs, owner, componentName) {const importSpec =owner.package === CORE_PACKAGE- ? resolveImportPath(coreDir, componentName)+ ? resolveImportPath(/** @type {string} */ (coreDir), componentName): `${owner.package}/${componentName}`;return {...docs,@@ -368,7 +390,7 @@ export async function component(name, options = {}) {}return {type: 'component.detail.source', data: {component: dirName, source: fs.readFileSync(owner.sourcePath, 'utf-8')}};}- const docs = await loadDocs(owner.docPath, {zh, dense, lang});+ const docs = /** @type {LoadedComponentDoc} */ (await loadDocs(owner.docPath, /** @type {LoadDocsOpts} */ ({zh, dense, lang})));if (props) {const p = docs.props || (docs.components ? docs.components.flatMap(c => c.props || []) : []);return {type: 'component.detail.props', data: p};@@ -389,7 +411,7 @@ export async function component(name, options = {}) {}return {type: 'component.detail.source', data: {component: dirName, source: fs.readFileSync(owner.sourcePath, 'utf-8')}};}- const docs = await loadDocs(owner.docPath, {zh, dense, lang});+ const docs = /** @type {LoadedComponentDoc} */ (await loadDocs(owner.docPath, /** @type {LoadDocsOpts} */ ({zh, dense, lang})));if (props) {const p = docs.props || (docs.components ? docs.components.flatMap(c => c.props || []) : []);return {type: 'component.detail.props', data: p};@@ -420,7 +442,7 @@ export async function component(name, options = {}) {const extDocPath = findExternalComponentDoc(ext.docsDir, dirName);if (extDocPath && extDocPath.endsWith('.doc.mjs')) {- const docs = await loadDocs(extDocPath, {zh, dense, lang});+ const docs = /** @type {LoadedComponentDoc} */ (await loadDocs(extDocPath, /** @type {LoadDocsOpts} */ ({zh, dense, lang})));if (props) {const p = docs.props || (docs.components ? docs.components.flatMap(c => c.props || []) : []);@@ -461,7 +483,7 @@ export async function component(name, options = {}) {if (showcase) {throw new AstryxError(`No showcase found for "${name}"`, undefined, ERROR_CODES.ERR_NO_SHOWCASE);}- const docs = await loadDocs(owner.docPath, {zh, dense, lang});+ const docs = /** @type {LoadedComponentDoc} */ (await loadDocs(owner.docPath, /** @type {LoadDocsOpts} */ ({zh, dense, lang})));if (props) {const p = docs.props || (docs.components ? docs.components.flatMap(c => c.props || []) : []);return {type: 'component.detail.props', data: p};@@ -546,12 +568,12 @@ export async function component(name, options = {}) {throw new AstryxError(`No .doc.mjs found for "${resolvedName}". The component needs a typed doc file.`, undefined, ERROR_CODES.ERR_NO_DOC);}- const docs = await loadDocs(readmePath, {zh, dense, lang});+ const docs = /** @type {LoadedComponentDoc} */ (await loadDocs(readmePath, /** @type {LoadDocsOpts} */ ({zh, dense, lang})));// ── Blocks mode ──────────────────────────────────────────────if (blocks) {const allBlocks = await findRelatedBlocks(dirName);- const toEntry = (b) => ({+ const toEntry = (/** @type {any} */ b) => ({name: b.dirName,displayName: b.name,description: b.description,@@ -561,7 +583,7 @@ export async function component(name, options = {}) {// Examples: blocks in the component's own directory, or// componentsUsed match for sub-components without a directory.- const ownDir = allBlocks.filter(b => path.basename(b.category) === dirName);+ const ownDir = allBlocks.filter((/** @type {any} */ b) => path.basename(b.category) === dirName);const examples = ownDir.length > 0? ownDir: allBlocks.filter(b => b.componentsUsed?.some(c => c === dirName));@@ -595,6 +617,7 @@ export async function component(name, options = {}) {: null;if (matchingComponent) {+ /** @type {LoadedComponentDoc & {parentDoc?: string, import?: string}} */const scoped = {name: dirName,description: matchingComponent.description,diff --git a/packages/cli/src/api/discover.mjs b/packages/cli/src/api/discover.mjsindex 70399b1326..7399388781 100644--- a/packages/cli/src/api/discover.mjs+++ b/packages/cli/src/api/discover.mjs@@ -14,18 +14,27 @@ import {levenshteinDistance} from '../lib/string-utils.mjs';import {AstryxError} from './error.mjs';import {ERROR_CODES} from '../lib/error-codes.mjs';+/**+ * @typedef {import('../lib/package-scanner.mjs').ScannedPackage} ScannedPackage+ */++/**+ * @param {unknown} docs+ * @returns {string | null}+ */function validateDocs(docs) {if (!docs || typeof docs !== 'object')return 'docs export is missing or not an object';- if (typeof docs.name !== 'string' || !docs.name)+ const d = /** @type {Record<string, any>} */ (docs);+ if (typeof d.name !== 'string' || !d.name)return 'docs.name is missing or not a string';- if (!docs.usage || typeof docs.usage.description !== 'string')+ if (!d.usage || typeof d.usage.description !== 'string')return 'docs.usage.description is missing or not a string';- if (docs.props && !Array.isArray(docs.props))+ if (d.props && !Array.isArray(d.props))return 'docs.props must be an array';- if (docs.components && !Array.isArray(docs.components))+ if (d.components && !Array.isArray(d.components))return 'docs.components must be an array';- if (docs.usage?.bestPractices && !Array.isArray(docs.usage.bestPractices))+ if (d.usage?.bestPractices && !Array.isArray(d.usage.bestPractices))return 'docs.usage.bestPractices must be an array';return null;}@@ -36,11 +45,21 @@ function validateDocs(docs) {* @param {boolean} [options.components]* @param {string} [options.lang]* @param {boolean} [options.zh]- * @returns {Promise<{type: string, data: unknown}>}+ * @returns {Promise<+ * import('../types/discover').DiscoverListResponse |+ * import('../types/discover').DiscoverDetailResponse |+ * import('../types/discover').DiscoverDetailDocResponse |+ * import('../types/discover').DiscoverSearchResponse+ * >}*/export async function discover(query, options = {}) {const {lang = null, zh = false} = options;const project = await Project.load();+ const loadedIntegrations =+ /** @type {import('../lib/integrations.mjs').LoadedIntegration[]} */ (+ project.loadedIntegrations+ );+ /** @param {ScannedPackage} pkg */const toEntry = pkg => ({name: pkg.name,category: pkg.category,@@ -52,7 +71,7 @@ export async function discover(query, options = {}) {// External packages come from configured integrations that declare a// components root. Each becomes a scannable package keyed by its docsDir.- const explicitPackages = project.loadedIntegrations+ const explicitPackages = loadedIntegrations.filter(integration => integration.components).map(integration => ({name: integration.name,@@ -64,7 +83,10 @@ export async function discover(query, options = {}) {return {type: 'discover.list', data: [], meta: {configured: false}};}- const packages = scanAllPackages([], explicitPackages);+ const packages = scanAllPackages(+ [],+ /** @type {ScannedPackage[]} */ (/** @type {unknown} */ (explicitPackages)),+ );if (packages.length === 0) {return {type: 'discover.list', data: [], meta: {configured: true}};@@ -105,7 +127,7 @@ export async function discover(query, options = {}) {return await loadAndValidate(exact, {lang, zh});}- const substringMatches = [];+ const substringMatches = /** @type {Array<{pkg: ScannedPackage, comp: string}>} */ ([]);for (const pkg of packages) {for (const comp of pkg.components) {if (comp.toLowerCase().includes(lower)) {@@ -134,7 +156,7 @@ export async function discover(query, options = {}) {}// Fuzzy fallback- const allComponents = [];+ const allComponents = /** @type {Array<{pkg: ScannedPackage, comp: string}>} */ ([]);for (const pkg of packages) {for (const comp of pkg.components) {allComponents.push({pkg, comp});@@ -167,6 +189,13 @@ export async function discover(query, options = {}) {);}+/**+ * @param {ScannedPackage[]} packages+ * @param {string} compName+ * @param {string} pkgName+ * @param {{lang?: string|null, zh?: boolean}} opts+ * @returns {Promise<import('../types/discover').DiscoverDetailDocResponse>}+ */async function resolveComponentDocs(packages, compName, pkgName, {lang, zh}) {const pkg = packages.find(p => p.name === pkgName);if (!pkg)@@ -202,13 +231,21 @@ async function resolveComponentDocs(packages, compName, pkgName, {lang, zh}) {return await loadAndValidate(result, {lang, zh});}+/**+ * @param {{docPath: string, componentName: string, pkg: ScannedPackage}} result+ * @param {{lang?: string|null, zh?: boolean}} opts+ * @returns {Promise<import('../types/discover').DiscoverDetailDocResponse>}+ */async function loadAndValidate(result, {lang, zh}) {let docs;try {- docs = await loadDocs(result.docPath, {zh, lang});+ docs = await loadDocs(+ result.docPath,+ /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({zh, lang}),+ );} catch (e) {throw new AstryxError(- `Failed to load docs for ${result.componentName}: ${e.message}`,+ `Failed to load docs for ${result.componentName}: ${/** @type {any} */ (e).message}`,undefined,ERROR_CODES.ERR_INVALID_DOC,);diff --git a/packages/cli/src/api/docs.mjs b/packages/cli/src/api/docs.mjsindex 4230db403c..85af93a041 100644--- a/packages/cli/src/api/docs.mjs+++ b/packages/cli/src/api/docs.mjs@@ -13,7 +13,11 @@ import {ERROR_CODES} from '../lib/error-codes.mjs';const DOCS_DIR = path.join(CLI_ROOT, 'docs');+/**+ * @returns {Record<string, string>}+ */function discoverTopics() {+ /** @type {Record<string, string>} */const topics = {};if (!fs.existsSync(DOCS_DIR)) return topics;for (const file of fs.readdirSync(DOCS_DIR)) {@@ -23,6 +27,11 @@ function discoverTopics() {return topics;}+/**+ * @param {string} docPath+ * @param {{lang?: string|null}} [opts]+ * @returns {Promise<import('../types/docs').DocsDetailResponse['data']>}+ */async function loadReferenceDocs(docPath, {lang} = {}) {const mod = await import(pathToFileURL(docPath).href);const docs = mod.docs;@@ -45,6 +54,7 @@ async function loadReferenceDocs(docPath, {lang} = {}) {// printed the colour table under a "Spacing" heading (#2182). An overlay may// now cover any subset of sections, in any order; sections it does not name// keep their base content.+ /** @type {Map<string, any>} */const bySection = new Map();for (const ts of translation.sections ?? []) {if (ts?.section != null) bySection.set(ts.section, ts);@@ -53,32 +63,43 @@ async function loadReferenceDocs(docPath, {lang} = {}) {return {...docs,description: translation.description || docs.description,- sections: docs.sections.map(section => {- const ts = bySection.get(section.title);- if (!ts) return section;- return {- ...section,- title: ts.title || section.title,- content: section.content.map((block, bi) => {- const tb = ts.content?.[bi];- if (!tb) return block;- if (tb.type === 'prose' && block.type === 'prose') return {...block, text: tb.text};- if (tb.type === 'list' && block.type === 'list') return {...block, items: tb.items};- return block;- }),- };- }),+ sections: docs.sections.map(+ (/** @type {import('../../../core/src/docs-types').ReferenceSection} */ section) => {+ const ts = bySection.get(section.title);+ if (!ts) return section;+ return {+ ...section,+ title: ts.title || section.title,+ content: section.content.map(+ (+ /** @type {import('../../../core/src/docs-types').ContentBlock} */ block,+ /** @type {number} */ bi,+ ) => {+ const tb = ts.content?.[bi];+ if (!tb) return block;+ if (tb.type === 'prose' && block.type === 'prose') return {...block, text: tb.text};+ if (tb.type === 'list' && block.type === 'list') return {...block, items: tb.items};+ return block;+ },+ ),+ };+ },+ ),};}/*** Resolve token-ref blocks by inlining the referenced section's table.* This allows section docs to reference token tables without duplicating data.+ * @param {import('../types/docs').DocsDetailResponse['data']} docsData+ * @param {Record<string, string>} topics+ * @returns {Promise<import('../types/docs').DocsDetailResponse['data']>}*/async function resolveTokenRefs(docsData, topics) {const resolved = {...docsData, sections: [...docsData.sections]};for (let si = 0; si < resolved.sections.length; si++) {const section = resolved.sections[si];+ /** @type {import('../../../core/src/docs-types').ContentBlock[]} */const newContent = [];for (const block of section.content) {if (block.type === 'token-ref') {@@ -90,7 +111,8 @@ async function resolveTokenRefs(docsData, topics) {const refMod = await import(pathToFileURL(refPath).href);const refDocs = refMod.docs;const refSection = refDocs.sections.find(- s => s.title.toLowerCase() === block.section.toLowerCase(),+ (/** @type {import('../../../core/src/docs-types').ReferenceSection} */ s) =>+ s.title.toLowerCase() === block.section.toLowerCase(),);if (!refSection) {newContent.push({type: 'prose', text: `[token-ref: section "${block.section}" not found in "${block.topic}"]`});@@ -125,7 +147,11 @@ async function resolveTokenRefs(docsData, topics) {* @param {string} [options.lang]* @param {boolean} [options.zh]* @param {boolean} [options.dense]- * @returns {Promise<{type: string, data: unknown}>}+ * @returns {Promise<+ * import('../types/docs').DocsListResponse |+ * import('../types/docs').DocsDetailResponse |+ * import('../types/docs').DocsDetailSectionResponse+ * >}*/export async function docs(topic, section, options = {}) {const {lang = null, zh = false, dense = false} = options;diff --git a/packages/cli/src/api/doctor.mjs b/packages/cli/src/api/doctor.mjsindex adc94ec156..3c13be9421 100644--- a/packages/cli/src/api/doctor.mjs+++ b/packages/cli/src/api/doctor.mjs@@ -49,7 +49,7 @@ const _require = createRequire(import.meta.url);* @typedef {object} DoctorContext* @property {string} cwd - Directory to diagnose.* @property {string} nodeVersion - Running Node version.- * @property {string|null} coreDir - Resolved @astryxdesign/core directory, or null.+ * @property {string|null} coreDir - Resolved core package directory, or null.* @property {string|null} configPath - Resolved astryx.config.mjs path, or null.* @property {string|null} configTheme - theme value read from config, or null.*/@@ -104,6 +104,7 @@ function findNodeModules(startDir) {*/function findThemePackages(cwd) {const nm = findNodeModules(cwd);+ /** @type {Array<{name: string, version: string|null}>} */const found = [];if (!nm) return found;const scopeDir = path.join(nm, '@astryxdesign');@@ -317,7 +318,7 @@ export async function checkConfig(ctx) {id: 'config',label: 'astryx.config.mjs',status: 'fail',- message: `astryx.config.mjs failed to load: ${err.message}`,+ message: `astryx.config.mjs failed to load: ${/** @type {any} */ (err).message}`,fix: 'Fix the syntax/runtime error in astryx.config.mjs so it imports cleanly.',};}@@ -490,7 +491,8 @@ export async function runChecks(options = {}) {let configTheme = null;try {const project = await Project.load(cwd);- configTheme = project.config?.theme ?? null;+ configTheme =+ /** @type {{theme?: string}} */ (project.config ?? {}).theme ?? null;} catch {// Best-effort: a missing/invalid config leaves configTheme null.}@@ -504,6 +506,7 @@ export async function runChecks(options = {}) {configTheme,};+ /** @type {DoctorCheck[]} */const checks = [];// checkConfig is async; run it in its declared slot (after themes).for (const fn of SYNC_CHECKS) {diff --git a/packages/cli/src/api/hook.mjs b/packages/cli/src/api/hook.mjsindex abacb583e0..73f4725899 100644--- a/packages/cli/src/api/hook.mjs+++ b/packages/cli/src/api/hook.mjs@@ -72,7 +72,7 @@ export async function hook(name, options = {}) {const docPath = findHookDoc(coreDir, hookName);if (docPath) {try {- const docs = await loadDocs(docPath, {zh, lang});+ const docs = await loadDocs(docPath, /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({zh, lang}));entries.push({name: hookName,description: docs.usage?.description || '',@@ -94,7 +94,7 @@ export async function hook(name, options = {}) {const docPath = findHookDoc(coreDir, hookName);if (docPath) {try {- entries.push(await loadDocs(docPath, {zh, lang}));+ entries.push(await loadDocs(docPath, /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({zh, lang})));} catch {entries.push({name: hookName});}@@ -119,7 +119,7 @@ export async function hook(name, options = {}) {const docPath = findHookDoc(coreDir, hookName);if (docPath) {try {- const docs = await loadDocs(docPath, {zh, lang});+ const docs = await loadDocs(docPath, /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({zh, lang}));result[cat].push({name: hookName,description: docs.usage?.description || '',@@ -145,7 +145,7 @@ export async function hook(name, options = {}) {const docPath = findHookDoc(coreDir, hookName);if (docPath) {try {- result[cat].push(await loadDocs(docPath, {zh, lang}));+ result[cat].push(await loadDocs(docPath, /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({zh, lang})));} catch {result[cat].push({name: hookName});}@@ -186,7 +186,7 @@ export async function hook(name, options = {}) {);}- const docs = await loadDocs(docPath, {zh, lang});+ const docs = await loadDocs(docPath, /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({zh, lang}));if (params) {return {type: 'hook.detail.params', data: docs.params || []};diff --git a/packages/cli/src/api/layout.mjs b/packages/cli/src/api/layout.mjsindex 5a29f7c952..e8fb3cb3bd 100644--- a/packages/cli/src/api/layout.mjs+++ b/packages/cli/src/api/layout.mjs@@ -27,14 +27,31 @@ import {buildRegistry, ALIAS_TABLE} from '../lib/xle/registry.mjs';import {discoverTemplates, stripTemplateAssetRefs} from './template.mjs';import {Project} from '../lib/project.mjs';+/**+ * @typedef {object} LayoutBlock+ * @property {string} dirName+ * @property {string} name+ * @property {'template'|'component'} kind+ * @property {string} [type]+ * @property {string} [description]+ * @property {string} [category]+ * @property {string} [importPath]+ * @property {string} [filePath]+ * @property {boolean} [isDefault]+ */+/*** The catalog a `{hint}` can resolve to: template blocks (spliced inline) plus* any app-registered local components from astryx.config.mjs* `experimental.xle.components` (imported by name). App components are how XLE* reaches domain pieces — the KpiCard/chart/drawer set that the* @astryxdesign/core registry can't see.+ *+ * @param {string} cwd+ * @returns {Promise<LayoutBlock[]>}*/async function loadBlocks(cwd) {+ /** @type {LayoutBlock[]} */const blocks = [];try {const all = await discoverTemplates(cwd);@@ -44,6 +61,7 @@ async function loadBlocks(cwd) {}try {const project = await Project.load(cwd);+ /** @type {Record<string, {from?: string, description?: string, default?: boolean}>} */const components = project.config.experimental?.xle?.components ?? {};for (const [name, spec] of Object.entries(components)) {const importPath = spec.from;@@ -65,11 +83,17 @@ async function loadBlocks(cwd) {return blocks;}+/** @param {string} name */const normKey = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, '');-/** Collect the block names referenced by {hints} anywhere in the doc. */+/**+ * Collect the block names referenced by {hints} anywhere in the doc.+ * @param {import('../lib/xle/xle-ast').XLEDoc} doc+ */function collectHintNames(doc) {+ /** @type {Set<string>} */const names = new Set();+ /** @param {import('../lib/xle/xle-ast').XLEItem} node */const visitNode = (node) => {if (!node || node.kind === 'group') {(node?.children || []).forEach(visit);@@ -77,11 +101,17 @@ function collectHintNames(doc) {}if (node.hint?.block) names.add(node.hint.block.name);for (const slot of node.slots || []) {- if (slot.value?.hint?.block) names.add(slot.value.hint.block.name);- (slot.value?.subexpr || []).forEach(visit);+ const value = slot.value;+ if (value && typeof value === 'object' && 'hint' in value && value.hint?.block) {+ names.add(value.hint.block.name);+ }+ if (value && typeof value === 'object' && 'subexpr' in value) {+ (value.subexpr || []).forEach(visit);+ }}(node.children || []).forEach(visit);};+ /** @param {import('../lib/xle/xle-ast').XLEItem} item */const visit = (item) => (item?.kind === 'group' ? item.children.forEach(visit) : visitNode(item));doc.roots.forEach(visit);doc.overlays.forEach(visit);@@ -92,24 +122,30 @@ function collectHintNames(doc) {* Build the blockModules map expand() needs: import-mode for app components,* splice-mode (reading + asset-stripping the block source) for template blocks.* Only blocks actually referenced are read.+ *+ * @param {import('../lib/xle/xle-ast').XLEDoc} doc+ * @param {LayoutBlock[]} blocks+ * @returns {Map<string, import('../lib/xle/xle-ast').BlockModule>}*/function buildBlockModules(doc, blocks) {const referenced = collectHintNames(doc);if (referenced.size === 0) return new Map();const byKey = new Map(blocks.map(b => [normKey(b.dirName), b]));+ /** @type {Map<string, import('../lib/xle/xle-ast').BlockModule>} */const modules = new Map();for (const name of referenced) {const block = byKey.get(normKey(name));if (!block) continue;if (block.kind === 'component') {- modules.set(name, {mode: 'import', componentName: block.name, importPath: block.importPath, isDefault: block.isDefault});+ modules.set(name, /** @type {import('../lib/xle/xle-ast').BlockModule} */ (/** @type {unknown} */ ({mode: 'import', componentName: block.name, importPath: block.importPath, isDefault: block.isDefault})));} else if (block.filePath && fs.existsSync(block.filePath)) {- modules.set(name, {mode: 'splice', componentName: block.dirName, source: stripTemplateAssetRefs(fs.readFileSync(block.filePath, 'utf-8'))});+ modules.set(name, /** @type {import('../lib/xle/xle-ast').BlockModule} */ ({mode: 'splice', componentName: block.dirName, source: stripTemplateAssetRefs(fs.readFileSync(block.filePath, 'utf-8'))}));}}return modules;}+/** @param {import('../lib/xle/xle-ast').RawIssue} issue */function formatIssue(issue) {const where = issue.line != null ? `line ${issue.line}: ` : '';return `${where}${issue.message}`;@@ -118,11 +154,17 @@ function formatIssue(issue) {/*** Parse + validate, throwing structured XDSErrors on failure.* Returns {doc, registry, blocks, warnings}.+ *+ * @param {string} expression+ * @param {{form?: 'compact'|'outline'|'auto', loose?: boolean, cwd?: string}} [options]*/async function analyze(expression, {form = 'auto', loose = false, cwd = process.cwd()} = {}) {- const registry = await buildRegistry({cwd});+ const registry = /** @type {import('../lib/xle/xle-ast').Registry} */ (+ /** @type {unknown} */ (await buildRegistry({cwd}))+ );const blocks = await loadBlocks(cwd);+ /** @type {import('../lib/xle/xle-ast').XLEDoc} */let doc;try {doc = parse(expression, {form});@@ -212,6 +254,9 @@ export async function layoutExpand(expression, options = {}) {/*** `astryx layout check "<expr>" [--form compact|outline]`* Validates without expanding; echoes both canonical surfaces.+ *+ * @param {string} expression+ * @param {{form?: 'compact'|'outline'|'auto', loose?: boolean, cwd?: string}} [options]*/export async function layoutCheck(expression, options = {}) {const {form = 'auto', loose = false, cwd = process.cwd()} = options;@@ -233,16 +278,20 @@ export async function layoutCheck(expression, options = {}) {/*** `astryx layout grammar` — the agent cheatsheet, with the alias table* generated from this branch's registry (never hand-maintained).+ *+ * @param {{cwd?: string}} [options]*/export async function layoutGrammar(options = {}) {const {cwd = process.cwd()} = options;const registry = await buildRegistry({cwd});+ /** @type {string[]} */const aliasLines = [];+ /** @type {Map<string, string[]>} */const byTarget = new Map();for (const [alias, target] of registry.aliases) {if (!byTarget.has(target)) byTarget.set(target, []);- byTarget.get(target).push(alias);+ byTarget.get(target)?.push(alias);}for (const [target, aliases] of [...byTarget.entries()].sort(([a], [b]) => a.localeCompare(b))) {aliasLines.push(`${aliases.join('/')}=${target}`);diff --git a/packages/cli/src/api/search.mjs b/packages/cli/src/api/search.mjsindex 16b64829cd..03dfc6c359 100644--- a/packages/cli/src/api/search.mjs+++ b/packages/cli/src/api/search.mjs@@ -46,6 +46,21 @@ import {AstryxError} from './error.mjs';const DOCS_DIR = path.join(CLI_ROOT, 'docs');+/**+ * A search candidate gathered from one content domain. Extra underscore-+ * prefixed fields carry domain-specific payload used only by {@link toResult}.+ * @typedef {object} Candidate+ * @property {'component'|'hook'|'doc'|'template'} domain+ * @property {string} name+ * @property {string[]} [keywords]+ * @property {string} [description]+ * @property {string[]} [prose]+ * @property {string} [_import]+ * @property {string} [_title]+ * @property {string} [_displayName]+ * @property {'page'|'block'} [_kind]+ */+/*** Synonym / intent map: product-language terms an agent is likely to type,* expanded to the catalog's vocabulary so oblique queries still rank. Keys and@@ -72,10 +87,19 @@ const SYNONYMS = {// Flatten into a token -> Set(expansions) lookup (bidirectional).const SYNONYM_INDEX = (() => {+ /** @type {Map<string, Set<string>>} */const idx = new Map();+ /**+ * @param {string} a+ * @param {string} b+ */const add = (a, b) => {- if (!idx.has(a)) idx.set(a, new Set());- idx.get(a).add(b);+ let set = idx.get(a);+ if (!set) {+ set = new Set();+ idx.set(a, set);+ }+ set.add(b);};for (const [key, vals] of Object.entries(SYNONYMS)) {for (const v of vals) {@@ -159,6 +183,8 @@ const MIN_TOKEN_SCORE = 50;/*** Best score for a token against a candidate, fanning out through synonyms* (synonym hits are discounted so a direct hit always wins).+ * @param {string} tok+ * @param {Candidate} candidate* @returns {{score: number, reason: string} | null}*/function bestForToken(tok, candidate) {@@ -176,6 +202,12 @@ function bestForToken(tok, candidate) {return best;}+/**+ * @param {string} term - Lowercased full query.+ * @param {string[]} tokens - Content tokens from tokenizeQuery(term).+ * @param {Candidate} candidate+ * @returns {{score: number, reason: string} | null}+ */export function scoreQuery(term, tokens, candidate) {const full = scoreCandidate(term, candidate);@@ -192,6 +224,7 @@ export function scoreQuery(term, tokens, candidate) {// strong hits, then reward coverage so candidates matching more terms win.let sum = 0;let matched = 0;+ /** @type {string[]} */const hitTerms = [];for (const tok of tokens) {const h = bestForToken(tok, candidate);@@ -235,6 +268,10 @@ export function scoreQuery(term, tokens, candidate) {export function scoreCandidate(term, {name, keywords = [], description = '', prose = []}) {let best = 0;let reason = '';+ /**+ * @param {number} score+ * @param {string} why+ */const consider = (score, why) => {if (score > best) {best = score;@@ -299,7 +336,12 @@ export function scoreCandidate(term, {name, keywords = [], description = '', proreturn best > 0 ? {score: best, reason} : null;}-/** Load a doc module's `docs`/`doc` export, swallowing errors. */+/**+ * Load a doc module's `docs`/`doc` export, swallowing errors.+ * @param {string} docPath+ * @param {string} [exportName]+ * @returns {Promise<any>}+ */async function loadModuleDoc(docPath, exportName = 'docs') {try {const mod = await import(pathToFileURL(docPath).href);@@ -313,13 +355,16 @@ async function loadModuleDoc(docPath, exportName = 'docs') {* Build component candidates: name + keywords + usage/description from the* component's .doc.mjs.* @param {string} coreDir+ * @returns {Promise<Candidate[]>}*/async function gatherComponents(coreDir) {const grouped = discoverComponents(coreDir);const names = Object.values(grouped).flat();+ /** @type {Candidate[]} */const candidates = [];for (const comp of names) {const readme = findComponentReadme(coreDir, comp);+ /** @type {string[]} */let keywords = [];let description = '';if (readme && readme.endsWith('.doc.mjs')) {@@ -344,13 +389,16 @@ async function gatherComponents(coreDir) {* Build hook candidates: name + keywords + usage/description from the hook's* .doc.mjs.* @param {string} coreDir+ * @returns {Promise<Candidate[]>}*/async function gatherHooks(coreDir) {const grouped = discoverHooks(coreDir);const names = Object.values(grouped).flat();+ /** @type {Candidate[]} */const candidates = [];for (const hookName of names) {const docPath = findHookDoc(coreDir, hookName);+ /** @type {string[]} */let keywords = [];let description = '';let importPath = '@astryxdesign/core/hooks';@@ -373,9 +421,13 @@ async function gatherHooks(coreDir) {return candidates;}-/** Build doc-topic candidates: topic name + description + section prose. */+/**+ * Build doc-topic candidates: topic name + description + section prose.+ * @returns {Promise<Candidate[]>}+ */async function gatherDocs() {if (!fs.existsSync(DOCS_DIR)) return [];+ /** @type {Candidate[]} */const candidates = [];for (const file of fs.readdirSync(DOCS_DIR)) {const match = file.match(/^([\w-]+)\.doc\.mjs$/);@@ -383,6 +435,7 @@ async function gatherDocs() {const topic = match[1];const doc = await loadModuleDoc(path.join(DOCS_DIR, file));let description = '';+ /** @type {string[]} */const prose = [];if (doc) {description = doc.description || '';@@ -405,7 +458,11 @@ async function gatherDocs() {return candidates;}-/** Build template candidates (page + block) from the template discovery API. */+/**+ * Build template candidates (page + block) from the template discovery API.+ * @param {string} cwd+ * @returns {Promise<Candidate[]>}+ */async function gatherTemplates(cwd) {let templates;try {@@ -444,7 +501,7 @@ async function gatherTemplates(cwd) {* carries enough to act on it: the domain, name, a one-line description, and* the follow-up command (and import path where relevant).*- * @param {object} c - candidate+ * @param {Candidate} c - candidate* @param {number} score* @param {string} reason*/@@ -522,6 +579,7 @@ export async function search(query, options = {}) {}// Gather candidates from each requested domain in parallel.+ /** @param {string} d */const wants = d => !type || type === d;const [components, hooks, docTopics, templates] = await Promise.all([wants('component') ? gatherComponents(coreDir) : [],@@ -543,6 +601,7 @@ export async function search(query, options = {}) {}// Sort by score desc, then domain (stable order), then name.+ /** @type {Record<string, number>} */const domainOrder = {component: 0, hook: 1, doc: 2, template: 3};scored.sort((a, b) =>diff --git a/packages/cli/src/api/template.mjs b/packages/cli/src/api/template.mjsindex 558de67caf..76511b0e91 100644--- a/packages/cli/src/api/template.mjs+++ b/packages/cli/src/api/template.mjs@@ -22,6 +22,39 @@ import {Project} from '../lib/project.mjs';/** Identity used for core (built-in) templates in package-scoped listings. */const CORE_PACKAGE = '@astryxdesign/core';+/**+ * A discovered template (page or block), normalized across core, external, and+ * integration sources. Not every source populates every field, so+ * source-specific extras (`aspectRatio`, `isShowcase`, `package`) are optional.+ * @typedef {object} DiscoveredTemplate+ * @property {'page'|'block'} type+ * @property {string} dirName+ * @property {string} name+ * @property {string} description+ * @property {string} [category]+ * @property {boolean} [isReady]+ * @property {boolean} [scaffold]+ * @property {number} [aspectRatio]+ * @property {string[]} [componentsUsed]+ * @property {boolean} [isShowcase]+ * @property {string} filePath+ * @property {string} docPath+ * @property {string} [package]+ */++/**+ * An integration-template discovery error.+ * @typedef {object} TemplateDiscoveryError+ * @property {string} package+ * @property {string} [template]+ * @property {string} message+ */++/**+ * The loaded metadata object from a template spec (loose — authored shape).+ * @typedef {Record<string, any> | undefined | null} TemplateDocModule+ */+/*** Canonical basename suffixes for template-spec files, in precedence order.* A template spec exports a `createBlockTemplate`/`createPageTemplate` result@@ -60,6 +93,7 @@ function matchedTemplateSuffix(file) {*/const TEMPLATE_SUFFIX_RE = /\.(template|doc)\.(ts|mjs|js)$/;+/** @type {ReturnType<typeof createJiti> | undefined} */let jitiInstance;/** Lazily-created jiti for loading `.ts` template specs (JSX-capable). */function getJiti() {@@ -69,7 +103,6 @@ function getJiti() {return jitiInstance;}-/*** Load an integration template doc module and validate it against the template* envelope at the load boundary. Default export only — `.ts` via jiti,@@ -145,7 +178,7 @@ export function stripTemplateAssetRefs(source) {* native dynamic import. Returns null if the file does not exist.** @param {string} docPath absolute path to the spec file- * @returns {Promise<Record<string, unknown> | undefined | null>}+ * @returns {Promise<TemplateDocModule>}*/async function loadDocModule(docPath) {if (!fs.existsSync(docPath)) return null;@@ -159,6 +192,7 @@ async function loadDocModule(docPath) {export {discoverAll as discoverTemplates};export function listTemplates() {+ /** @type {string[]} */const all = [];if (fs.existsSync(PAGES_DIR)) {all.push(@@ -171,7 +205,13 @@ export function listTemplates() {return all.sort();}+/**+ * @param {string} dir+ * @param {RegExp} pattern+ * @returns {string[]}+ */function findDocFiles(dir, pattern) {+ /** @type {string[]} */const results = [];if (!fs.existsSync(dir)) return results;for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {@@ -205,6 +245,7 @@ async function discoverPages() {.readdirSync(PAGES_DIR, {withFileTypes: true}).filter(e => e.isDirectory());+ /** @type {DiscoveredTemplate[]} */const templates = [];for (const dir of dirs) {const dirPath = path.join(PAGES_DIR, dir.name);@@ -228,9 +269,11 @@ async function discoverPages() {async function discoverBlocks() {const docFiles = findDocFiles(BLOCKS_DIR, TEMPLATE_SUFFIX_RE);+ /** @type {DiscoveredTemplate[]} */const blocks = [];for (const docPath of docFiles) {const suffix = matchedTemplateSuffix(docPath);+ if (!suffix) continue;const basename = path.basename(docPath, suffix);const tsxPath = path.join(path.dirname(docPath), basename + '.tsx');if (!fs.existsSync(tsxPath)) continue;@@ -262,6 +305,7 @@ async function discoverBlocks() {*/async function discoverExternalBlocks(cwd = process.cwd()) {const externals = discoverExternalPackages(cwd);+ /** @type {DiscoveredTemplate[]} */const blocks = [];for (const ext of externals) {@@ -269,6 +313,7 @@ async function discoverExternalBlocks(cwd = process.cwd()) {const docFiles = findDocFiles(ext.blocksDir, TEMPLATE_SUFFIX_RE);for (const docPath of docFiles) {const suffix = matchedTemplateSuffix(docPath);+ if (!suffix) continue;const basename = path.basename(docPath, suffix);const tsxPath = path.join(path.dirname(docPath), basename + '.tsx');if (!fs.existsSync(tsxPath)) continue;@@ -297,6 +342,7 @@ async function discoverExternalBlocks(cwd = process.cwd()) {/*** Discover all blocks — core + external packages.* @param {string} [cwd]+ * @returns {Promise<DiscoveredTemplate[]>}*/async function discoverAllBlocks(cwd = process.cwd()) {const [core, external] = await Promise.all([@@ -306,6 +352,10 @@ async function discoverAllBlocks(cwd = process.cwd()) {return [...core, ...external];}+/**+ * @param {string} [cwd]+ * @returns {Promise<DiscoveredTemplate[]>}+ */async function discoverAll(cwd = process.cwd()) {const [pages, blocks, integration] = await Promise.all([discoverPages(),@@ -323,7 +373,7 @@ async function discoverAll(cwd = process.cwd()) {* when the caller wants to warn about malformed integration templates.** @param {string} [cwd]- * @returns {Promise<{templates: object[], errors: {package: string, template?: string, message: string}[]}>}+ * @returns {Promise<{templates: DiscoveredTemplate[], errors: TemplateDiscoveryError[]}>}*/async function discoverAllWithErrors(cwd = process.cwd()) {const [pages, blocks, integration] = await Promise.all([@@ -348,8 +398,10 @@ export {discoverAllWithErrors};* @returns {string[]}*/function findIntegrationDocFiles(root) {+ /** @type {string[]} */const results = [];if (!fs.existsSync(root)) return results;+ /** @param {string} dir */const walk = dir => {for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {const full = path.join(dir, entry.name);@@ -377,16 +429,21 @@ function findIntegrationDocFiles(root) {* template is skipped (recorded in `errors`).** @param {string} [cwd]- * @returns {Promise<{templates: object[], errors: {package: string, template?: string, message: string}[]}>}+ * @returns {Promise<{templates: DiscoveredTemplate[], errors: TemplateDiscoveryError[]}>}*/async function discoverIntegrationTemplates(cwd = process.cwd()) {+ /** @type {DiscoveredTemplate[]} */const templates = [];+ /** @type {TemplateDiscoveryError[]} */const errors = [];let loadedIntegrations;try {const project = await Project.load(cwd);- loadedIntegrations = project.loadedIntegrations;+ loadedIntegrations =+ /** @type {import('../lib/integrations.mjs').LoadedIntegration[]} */ (+ project.loadedIntegrations+ );} catch {// Config load failures are surfaced elsewhere (discover/doctor); here we// simply contribute no integration templates.@@ -409,10 +466,12 @@ async function discoverIntegrationTemplates(cwd = process.cwd()) {* than thrown. Exposed for `validate-integration`.** @param {{name?: string, __spec?: string, templates?: string}} integration- * @returns {Promise<{templates: object[], errors: {package: string, template?: string, message: string}[]}>}+ * @returns {Promise<{templates: DiscoveredTemplate[], errors: TemplateDiscoveryError[]}>}*/export async function discoverIntegrationTemplatesForOne(integration) {+ /** @type {DiscoveredTemplate[]} */const templates = [];+ /** @type {TemplateDiscoveryError[]} */const errors = [];const root = integration?.templates;@@ -421,6 +480,7 @@ export async function discoverIntegrationTemplatesForOne(integration) {for (const docPath of findIntegrationDocFiles(root)) {const suffix = matchedTemplateSuffix(docPath);+ if (!suffix) continue;const id = path.relative(root, docPath).slice(0, -suffix.length)@@ -444,7 +504,7 @@ export async function discoverIntegrationTemplatesForOne(integration) {errors.push({package: pkgLabel,template: id,- message: `Template "${id}" failed to load: ${err.message}`,+ message: `Template "${id}" failed to load: ${/** @type {any} */ (err).message}`,});continue;}@@ -480,10 +540,15 @@ export async function discoverIntegrationTemplatesForOne(integration) {return {templates, errors};}+/**+ * @param {string} componentName+ * @param {string} [cwd]+ * @returns {Promise<DiscoveredTemplate[]>}+ */export async function findRelatedBlocks(componentName, cwd) {const blocks = await discoverAllBlocks(cwd);return blocks.filter(b =>- b.componentsUsed.some(c => c.toLowerCase() === componentName.toLowerCase()),+ (b.componentsUsed ?? []).some(c => c.toLowerCase() === componentName.toLowerCase()),);}@@ -506,7 +571,7 @@ export async function findShowcase(componentName, cwd, options) {return true;});- const toResult = b => ({+ const toResult = (/** @type {DiscoveredTemplate} */ b) => ({name: b.name,aspectRatio: b.aspectRatio,filePath: b.filePath,@@ -515,14 +580,14 @@ export async function findShowcase(componentName, cwd, options) {// Priority 1: own directory (components/Badge/ for "Badge")const dirMatch = showcases.find(b => {- const catDir = path.basename(b.category).toLowerCase();+ const catDir = path.basename(b.category ?? '').toLowerCase();return catDir === lc;});if (dirMatch) return toResult(dirMatch);// Priority 2: componentsUsed in any directory (ClickableCard in Card/)const usedMatch = showcases.find(b =>- b.componentsUsed.some(c => c.toLowerCase() === lc),+ (b.componentsUsed ?? []).some(c => c.toLowerCase() === lc),);if (usedMatch) return toResult(usedMatch);@@ -540,6 +605,10 @@ const UBIQUITOUS = new Set(['Icon',]);+/**+ * @param {string} pagePath+ * @returns {string[]}+ */export function extractComponents(pagePath) {const src = fs.readFileSync(pagePath, 'utf-8');// Match JSX opening tags, e.g. `<Section` or the legacy `<XDSSection`.@@ -548,6 +617,7 @@ export function extractComponents(pagePath) {// JSX-tag boundary keeps this precise (avoids matching imports/comments/// identifiers) while remaining prefix-agnostic.const tagRegex = /<(XDS)?([A-Z]\w+)/g;+ /** @type {string[]} */const matches = [];let m;while ((m = tagRegex.exec(src)) !== null) {@@ -617,10 +687,11 @@ const SPATIAL_PROPS = [* @returns {string[]}*/function extractSpatialAttrs(tagText) {+ /** @type {string[]} */const attrs = [];for (const name of SPATIAL_PROPS) {const eqMatch = tagText.match(new RegExp(`\\b${name}\\s*=\\s*`));- if (eqMatch) {+ if (eqMatch && eqMatch.index != null) {const start = eqMatch.index;let i = eqMatch.index + eqMatch[0].length;const rest = tagText.slice(i);@@ -662,13 +733,19 @@ function extractSpatialAttrs(tagText) {return attrs;}+/**+ * @param {string} source+ * @returns {string}+ */function extractSkeleton(source) {const lines = source.split('\n');+ /** @type {string[]} */const out = [];let depth = 0;let capturing = false;let inDefaultExport = false;const MAX_LINES = 35;+ /** @type {string[]} */const depthStack = [];for (let i = 0; i < lines.length; i++) {diff --git a/packages/cli/src/api/theme-add.mjs b/packages/cli/src/api/theme-add.mjsindex 8d995e2d68..8f957ec5fa 100644--- a/packages/cli/src/api/theme-add.mjs+++ b/packages/cli/src/api/theme-add.mjs@@ -21,19 +21,39 @@ const MANIFEST_PATH = path.join(THEMES_DIR, 'manifest.json');const META_COPYRIGHT_HEADER_RE =/^(\uFEFF?(?:#![^\r\n]*(?:\r?\n))?)\/\/ Copyright \(c\) Meta Platforms, Inc\. and affiliates\.\r?\n(?:\r?\n)*/;+/**+ * A single bundled theme entry from `templates/themes/manifest.json`.+ * @typedef {object} BundledTheme+ * @property {string} slug+ * @property {string} displayName+ * @property {string} description+ * @property {boolean} maintained+ * @property {string} entry+ * @property {string} exportName+ * @property {string[]} files+ */++/**+ * @param {string} source+ * @returns {string}+ */function stripCopyrightHeader(source) {return source.replace(META_COPYRIGHT_HEADER_RE, '$1');}-/** Parsed `themes` array from the bundle manifest (empty if not generated). */+/**+ * Parsed `themes` array from the bundle manifest (empty if not generated).+ * @returns {BundledTheme[]}+ */export function listThemes() {if (!fs.existsSync(MANIFEST_PATH)) return [];+ /** @type {{themes?: BundledTheme[]}} */let manifest;try {manifest = JSON.parse(fs.readFileSync(MANIFEST_PATH, 'utf-8'));} catch (err) {throw new AstryxError(- `Theme bundle manifest is unreadable (${MANIFEST_PATH}): ${err.message}`,+ `Theme bundle manifest is unreadable (${MANIFEST_PATH}): ${/** @type {any} */ (err).message}`,undefined,ERROR_CODES.ERR_NO_SOURCE,);@@ -41,12 +61,20 @@ export function listThemes() {return Array.isArray(manifest.themes) ? manifest.themes : [];}+/**+ * @param {string} [slug]+ * @returns {BundledTheme | undefined}+ */function findTheme(slug) {if (!slug) return undefined;const lc = String(slug).toLowerCase();return listThemes().find(t => t.slug.toLowerCase() === lc);}+/**+ * @param {string} slug+ * @returns {string}+ */function defaultTargetDir(slug) {return path.join('src', 'themes', slug);}@@ -160,7 +188,7 @@ export async function themeAdd(slug, options = {}) {}}throw new AstryxError(- `Failed to write theme files: ${err.message}`,+ `Failed to write theme files: ${/** @type {any} */ (err).message}`,undefined,ERROR_CODES.ERR_WRITE_FAILED,);diff --git a/packages/cli/src/api/validate-integration.mjs b/packages/cli/src/api/validate-integration.mjsindex ac2a191c13..ed8c65208d 100644--- a/packages/cli/src/api/validate-integration.mjs+++ b/packages/cli/src/api/validate-integration.mjs@@ -75,7 +75,8 @@ function error(code, message) {* @param {Issue[]} issues*/function checkRoots(resolved, issues) {- for (const kind of ['components', 'templates', 'codemods']) {+ const kinds = /** @type {const} */ (['components', 'templates', 'codemods']);+ for (const kind of kinds) {const root = resolved[kind];if (root == null) continue;if (!fs.existsSync(root)) {@@ -93,7 +94,7 @@ function checkRoots(resolved, issues) {* Validate the integration's codemods via the landed discovery. Discovery is* strict (throws on bad export / duplicate id); we convert any throw into an* `invalid_codemod` error.- * @param {object} integration loaded-integration-shaped object+ * @param {import('../lib/integrations.mjs').LoadedIntegration} integration loaded-integration-shaped object* @param {Issue[]} issues*/async function checkCodemods(integration, issues) {@@ -101,14 +102,14 @@ async function checkCodemods(integration, issues) {try {await discoverIntegrationCodemods([integration]);} catch (err) {- issues.push(error('invalid_codemod', err.message));+ issues.push(error('invalid_codemod', /** @type {any} */ (err).message));}}/*** Validate the integration's templates via the landed discovery. Per-template* problems are reported as `invalid_template` errors.- * @param {object} integration loaded-integration-shaped object+ * @param {import('../lib/integrations.mjs').LoadedIntegration} integration loaded-integration-shaped object* @param {Issue[]} issues*/async function checkTemplates(integration, issues) {@@ -119,7 +120,7 @@ async function checkTemplates(integration, issues) {issues.push(error('invalid_template', e.message));}} catch (err) {- issues.push(error('invalid_template', err.message));+ issues.push(error('invalid_template', /** @type {any} */ (err).message));}}@@ -132,7 +133,7 @@ async function checkTemplates(integration, issues) {* `discoverIntegrationComponents` returns ownership records and does not throw* on a missing same-stem source — it records `sourcePath: null`. We surface* each such record as an `invalid_component` error.- * @param {object} integration loaded-integration-shaped object+ * @param {import('../lib/integrations.mjs').LoadedIntegration} integration loaded-integration-shaped object* @param {Issue[]} issues*/async function checkComponents(integration, issues) {@@ -152,13 +153,13 @@ async function checkComponents(integration, issues) {}}} catch (err) {- issues.push(error('invalid_component', err.message));+ issues.push(error('invalid_component', /** @type {any} */ (err).message));}}/*** Run every contribution validator against a loaded-integration-shaped object.- * @param {object} integration+ * @param {import('../lib/integrations.mjs').LoadedIntegration} integration* @param {Issue[]} issues*/async function runContributionChecks(integration, issues) {@@ -181,7 +182,7 @@ async function runContributionChecks(integration, issues) {* contribution checks (roots + codemods/templates/components) because those can* regress independently of the manifest (a deleted directory, a broken template).*- * @param {object} loaded loaded-integration-shaped object+ * @param {import('../lib/integrations.mjs').LoadedIntegration} loaded loaded-integration-shaped object* @returns {Promise<Issue[]>}*/export async function validateLoadedIntegration(loaded) {@@ -210,6 +211,7 @@ export async function validateLoadedIntegration(loaded) {async function validateAtPackageDir(packageDir, identity) {/** @type {Issue[]} */const issues = [];+ /** @type {ValidateResult} */const result = {found: true,name: identity.name,@@ -254,10 +256,11 @@ async function validateAtPackageDir(packageDir, identity) {`Integration manifest (${path.basename(manifestFile)})`,);} catch (err) {- issues.push(error('invalid_manifest', err.message));+ issues.push(error('invalid_manifest', /** @type {any} */ (err).message));return result;}+ /** @param {string | null | undefined} value */const resolveRoot = value =>value == null ? undefined : path.resolve(packageDir, value);@@ -300,6 +303,7 @@ export async function validateLocalIntegration(cwd = process.cwd()) {return {found: false, issues: []};}+ /** @type {{name?: string, version?: string}} */let pkg = {};try {pkg = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8'));@@ -323,6 +327,7 @@ export async function validateInstalledIntegration(spec, cwd = process.cwd()) {const packageDir = resolvePackageDir(spec, cwd);const pkgJsonPath = path.join(packageDir, 'package.json');+ /** @type {{name?: string, version?: string}} */let pkg;try {pkg = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8'));diff --git a/packages/cli/src/codemods/ensure-jscodeshift.mjs b/packages/cli/src/codemods/ensure-jscodeshift.mjsindex efc2200847..24fb2e3456 100644--- a/packages/cli/src/codemods/ensure-jscodeshift.mjs+++ b/packages/cli/src/codemods/ensure-jscodeshift.mjs@@ -64,7 +64,7 @@ function installJscodeshift(silent = false) {log.success('jscodeshift installed.');return true;} catch (err) {- log.error(`Failed to install jscodeshift: ${err.message}`);+ log.error(`Failed to install jscodeshift: ${/** @type {any} */ (err).message}`);return false;}}diff --git a/packages/cli/src/codemods/integration-discovery.mjs b/packages/cli/src/codemods/integration-discovery.mjsindex b5d6864e07..49500fa181 100644--- a/packages/cli/src/codemods/integration-discovery.mjs+++ b/packages/cli/src/codemods/integration-discovery.mjs@@ -41,6 +41,7 @@ const CODEMOD_EXTENSIONS = ['.ts', '.mjs', '.js'];* @returns {Array<{id: string, file: string}>}*/function collectCodemodFiles(versionDir) {+ /** @type {Array<{id: string, file: string}>} */const out = [];/** @param {string} dir */@@ -74,7 +75,7 @@ function collectCodemodFiles(versionDir) {* for that version (across all integrations).*/export async function discoverIntegrationCodemods(loadedIntegrations = []) {- /** @type {Map<string, Array<{id: string, type: string, codemod: object, package: string}>>} */+ /** @type {Map<string, Array<{id: string, type: 'code'|'config', codemod: object, package: string}>>} */const byVersion = new Map();for (const integration of loadedIntegrations ?? []) {@@ -158,10 +159,12 @@ export async function discoverIntegrationCodemods(loadedIntegrations = []) {*/export function selectIntegrationCodemods(byVersion, from, to) {const versions = [...byVersion.keys()].sort(semverCompare);+ /** @type {Array<{version: string, codemods: Array<object>}>} */const results = [];for (const version of versions) {if (semverCompare(version, from) > 0 && semverCompare(version, to) <= 0) {- results.push({version, codemods: byVersion.get(version)});+ const codemods = byVersion.get(version);+ if (codemods) results.push({version, codemods});}}return results;diff --git a/packages/cli/src/codemods/integration-runner.mjs b/packages/cli/src/codemods/integration-runner.mjsindex 6cb2820820..0e6cb63a90 100644--- a/packages/cli/src/codemods/integration-runner.mjs+++ b/packages/cli/src/codemods/integration-runner.mjs@@ -31,15 +31,15 @@ import {* Optional codemods (isOptional) are skipped unless explicitly requested via* `codemod` (matched against the codemod id).*- * @param {Array<{version: string, codemods: Array<object>}>} versionGroups+ * @param {Array<{version: string, codemods: Array<import('../types/codemod').CodemodEntry>}>} versionGroups* @param {object} options* @param {boolean} options.apply* @param {string} options.path source directory to scan* @param {string} [options.codemod] run only this codemod id* @param {Set<string>} [options.skipCodemods] codemod ids to exclude- * @param {Function} options.jscodeshift+ * @param {import('../types/codemod').JscodeshiftFactory} options.jscodeshift* @param {boolean} [options.silent]- * @returns {{totalFilesChanged: number, totalTransformsApplied: number, writtenFiles: string[], errors: Array, skippedOptional: Array}}+ * @returns {{totalFilesChanged: number, totalTransformsApplied: number, writtenFiles: string[], errors: Array<{file: string, codemod: string, error: string}>, skippedOptional: Array<import('../types/codemod').CodemodEntry>}}*/export function runIntegrationCodemods(versionGroups,@@ -49,12 +49,17 @@ export function runIntegrationCodemods(let totalFilesChanged = 0;let totalTransformsApplied = 0;+ /** @type {string[]} */const writtenFiles = [];+ /** @type {Array<{file: string, codemod: string, error: string}>} */const errors = [];+ /** @type {Array<import('../types/codemod').CodemodEntry>} */const skippedOptional = [];// Flatten and split by type, preserving version ordering.+ /** @type {Array<import('../types/codemod').CodemodEntry>} */const configEntries = [];+ /** @type {Array<import('../types/codemod').CodemodEntry>} */const codeEntries = [];for (const {version, codemods} of versionGroups) {for (const entry of codemods) {diff --git a/packages/cli/src/codemods/registry.mjs b/packages/cli/src/codemods/registry.mjsindex 3d0c05ffbf..ccb471c1a6 100644--- a/packages/cli/src/codemods/registry.mjs+++ b/packages/cli/src/codemods/registry.mjs@@ -45,16 +45,18 @@ export const latestVersion = versions[versions.length - 1];** @param {string} from - Current version (exclusive)* @param {string} to - Target version (inclusive)- * @returns {Promise<Array<{version: string, transforms: Array<{name: string, module: Function}>}>>}+ * @returns {Promise<Array<{version: string, transforms: Array<{name: string, transform: import('../types/codemod').CodemodTransform, meta: {title: string, description?: string}}>}>>}*/export async function getTransformsBetween(from, to) {const applicable = versions.filter(v => semverCompare(v, from) > 0 && semverCompare(v, to) <= 0,);+ /** @type {Array<{version: string, transforms: Array<{name: string, transform: import('../types/codemod').CodemodTransform, meta: {title: string, description?: string}}>}>} */const results = [];for (const version of applicable) {const loader = registry.get(version);+ if (!loader) continue;const manifest = await loader();results.push({version,diff --git a/packages/cli/src/codemods/run-codemod.mjs b/packages/cli/src/codemods/run-codemod.mjsindex 63d7ae7e15..0a18915d86 100644--- a/packages/cli/src/codemods/run-codemod.mjs+++ b/packages/cli/src/codemods/run-codemod.mjs@@ -49,7 +49,9 @@ const PARSEABLE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js', '.mjs', '.cjs'];* @returns {string[]}*/export function findSourceFiles(dir) {+ /** @type {string[]} */const results = [];+ /** @param {string} currentDir */function walk(currentDir) {let entries;try {@@ -74,6 +76,7 @@ export function findSourceFiles(dir) {/*** No-op log surface for silent (`--json`) mode.* @param {boolean} silent+ * @returns {import('../types/codemod').CliLog}*/export function makeLog(silent) {return silent@@ -84,9 +87,9 @@ export function makeLog(silent) {/*** Apply a config codemod to the consumer's astryx.config.* file.*- * @param {object} entry normalized codemod entry {id, codemod, package}- * @param {{apply: boolean, log: object, jscodeshift: Function}} ctx- * @returns {{filesChanged: number, writtenFiles: string[], errors: Array}}+ * @param {import('../types/codemod').CodemodEntry} entry normalized codemod entry {id, codemod, package}+ * @param {{apply: boolean, log: import('../types/codemod').CliLog, jscodeshift: import('../types/codemod').JscodeshiftFactory}} ctx+ * @returns {import('../types/codemod').CodemodRunResult}*/export function runConfigCodemod(entry, {apply, log, jscodeshift}) {const {codemod, id, package: pkg} = entry;@@ -135,11 +138,12 @@ export function runConfigCodemod(entry, {apply, log, jscodeshift}) {errors: [],};} catch (err) {- log.error(` ✗ ${relativePath} — ${err.message}`);+ const message = /** @type {any} */ (err).message;+ log.error(` ✗ ${relativePath} — ${message}`);return {filesChanged: 0,writtenFiles: [],- errors: [{file: relativePath, codemod: name, error: err.message}],+ errors: [{file: relativePath, codemod: name, error: message}],};}}@@ -147,10 +151,10 @@ export function runConfigCodemod(entry, {apply, log, jscodeshift}) {/*** Apply a code codemod to discovered source files.*- * @param {object} entry normalized codemod entry {id, codemod, package}+ * @param {import('../types/codemod').CodemodEntry} entry normalized codemod entry {id, codemod, package}* @param {string[]} files- * @param {{apply: boolean, log: object, jscodeshift: Function}} ctx- * @returns {{filesChanged: number, writtenFiles: string[], errors: Array}}+ * @param {{apply: boolean, log: import('../types/codemod').CliLog, jscodeshift: import('../types/codemod').JscodeshiftFactory}} ctx+ * @returns {import('../types/codemod').CodemodRunResult}*/export function runCodeCodemod(entry, files, {apply, log, jscodeshift}) {const {codemod, id, package: pkg} = entry;@@ -158,7 +162,9 @@ export function runCodeCodemod(entry, files, {apply, log, jscodeshift}) {const extensions = new Set(codemod.fileExtensions ?? DEFAULT_CODE_EXTENSIONS);let filesChanged = 0;+ /** @type {string[]} */const writtenFiles = [];+ /** @type {Array<{file: string, codemod: string, error: string}>} */const errors = [];for (const filePath of files) {@@ -198,8 +204,9 @@ export function runCodeCodemod(entry, files, {apply, log, jscodeshift}) {log.warn(` ~ ${relativePath} (would change)`);}} catch (err) {- log.error(` ✗ ${relativePath} — ${err.message}`);- errors.push({file: relativePath, codemod: name, error: err.message});+ const message = /** @type {any} */ (err).message;+ log.error(` ✗ ${relativePath} — ${message}`);+ errors.push({file: relativePath, codemod: name, error: message});}}diff --git a/packages/cli/src/codemods/runner.mjs b/packages/cli/src/codemods/runner.mjsindex b76bbaaf9c..143024d2eb 100644--- a/packages/cli/src/codemods/runner.mjs+++ b/packages/cli/src/codemods/runner.mjs@@ -51,6 +51,7 @@ export function fixDirectiveCorruption(code) {* @returns {string[]}*/function findSourceFiles(dir) {+ /** @type {string[]} */const results = [];const extensions = new Set(['.tsx',@@ -65,6 +66,7 @@ function findSourceFiles(dir) {'.less',]);+ /** @param {string} currentDir */function walk(currentDir) {let entries;try {@@ -96,8 +98,9 @@ function findSourceFiles(dir) {** @param {string} result - The transformed source code* @param {string} source - The original source code- * @param {Function} j - jscodeshift instance (with parser configured)- * @returns {{ valid: boolean, reason?: string }}+ * @param {import('../types/codemod').JscodeshiftFactory} j - jscodeshift instance (with parser configured)+ * @param {{parse?: boolean}} [options]+ * @returns {{ valid: true } | { valid: false, reason: string }}*/export function validateOutput(result, source, j, {parse = true} = {}) {// Check 1: Re-parse the output — catches syntax-breaking corruption@@ -105,9 +108,10 @@ export function validateOutput(result, source, j, {parse = true} = {}) {try {j(result);} catch (parseError) {+ const message = /** @type {any} */ (parseError).message;return {valid: false,- reason: `transform produced unparseable output: ${parseError.message}`,+ reason: `transform produced unparseable output: ${message}`,};}}@@ -147,9 +151,9 @@ export function validateOutput(result, source, j, {parse = true} = {}) {* with the same `(file, api) => string | null | undefined` contract used by* `createConfigCodemod`.*- * @param {{name: string, transform: Function, meta: object, optional?: boolean}} transformEntry+ * @param {{name: string, transform: import('../types/codemod').CodemodTransform, meta: {title: string, description?: string, fileExtensions?: string[], codemodType?: string}, optional?: boolean}} transformEntry* @param {string} version- * @returns {{id: string, type: 'code'|'config', codemod: object, package: string, version: string}}+ * @returns {import('../types/codemod').CodemodEntry}*/function toUnifiedEntry(transformEntry, version) {const {name, transform, meta, optional} = transformEntry;@@ -171,14 +175,14 @@ function toUnifiedEntry(transformEntry, version) {/*** Run codemods against source files.*- * @param {Array<{version: string, transforms: Array}>} versionManifests+ * @param {Array<{version: string, transforms: Array<{name: string, transform: import('../types/codemod').CodemodTransform, meta: {title: string, description?: string, fileExtensions?: string[], codemodType?: string}, optional?: boolean}>}>} versionManifests* @param {object} options* @param {boolean} options.apply - Write changes to disk* @param {string} options.path - Source directory to scan* @param {string|undefined} options.codemod - Run only this specific transform* @param {Set<string>} [options.skipCodemods] - Transform names to exclude* @param {boolean} [options.silent] - Suppress all human-facing output (for --json)- * @returns {{totalFilesChanged: number, totalTransformsApplied: number, totalValidationBlocked: number, writtenFiles: string[], errors: Array, skippedOptional: Array}}+ * @returns {Promise<{totalFilesChanged: number, totalTransformsApplied: number, totalValidationBlocked: number, writtenFiles: string[], errors: Array<{file: string, codemod: string, error: string}>, skippedOptional: Array<{name: string, meta: {title: string, description?: string, fileExtensions?: string[], codemodType?: string}, version: string}>} | {ok: false, reason: string, resolvedPath: string}>}*/export async function runCodemods(versionManifests,@@ -208,11 +212,11 @@ export async function runCodemods(return {ok: false, reason: 'source_path_missing', resolvedPath};}+ /** @type {string[]} */let files = [];if (sourcePathExists) {log.step(`Scanning ${resolvedPath} for source files...`);files = findSourceFiles(resolvedPath);-if (files.length === 0) {log.warn('No source files found.');} else {@@ -223,15 +227,20 @@ export async function runCodemods(}// Dynamically import jscodeshift- const jscodeshift = (await import('jscodeshift')).default;+ const jscodeshift =+ /** @type {import('../types/codemod').JscodeshiftFactory} */ (+ (await import('jscodeshift')).default+ );let totalFilesChanged = 0;let totalTransformsApplied = 0;let totalValidationBlocked = 0;+ /** @type {Array<{file: string, codemod: string, error: string}>} */const errors = [];+ /** @type {string[]} */const writtenFiles = [];+ /** @type {Array<{name: string, meta: {title: string, description?: string, fileExtensions?: string[], codemodType?: string}, version: string}>} */const skippedOptional = [];-for (const {version, transforms} of versionManifests) {log.step(`Applying v${version} codemods...`);@@ -333,8 +342,9 @@ export async function runCodemods(}}} catch (err) {- log.error(` ✗ ${relativePath} — ${err.message}`);- errors.push({file: relativePath, codemod: name, error: err.message});+ const message = /** @type {any} */ (err).message;+ log.error(` ✗ ${relativePath} — ${message}`);+ errors.push({file: relativePath, codemod: name, error: message});}}diff --git a/packages/cli/src/codemods/transforms/v0.0.10/remove-size-props.mjs b/packages/cli/src/codemods/transforms/v0.0.10/remove-size-props.mjsindex b09b7f83ec..9616fa1441 100644--- a/packages/cli/src/codemods/transforms/v0.0.10/remove-size-props.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.10/remove-size-props.mjs@@ -32,6 +32,11 @@ export const meta = {pr: '#966',};+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);@@ -40,7 +45,7 @@ export default function transformer(file, api) {// 1. Remove size JSX prop from target componentsroot.find(j.JSXOpeningElement)- .filter((path) => {+ .filter((/** @type {any} */ path) => {const name = path.node.name;// Handle simple names like <XDSStatusDot>if (name.type === 'JSXIdentifier') {@@ -48,10 +53,10 @@ export default function transformer(file, api) {}return false;})- .forEach((path) => {+ .forEach((/** @type {any} */ path) => {const attrs = path.node.attributes;const sizeIdx = attrs.findIndex(- (attr) =>+ (/** @type {any} */ attr) =>attr.type === 'JSXAttribute' &&attr.name &&attr.name.name === 'size',@@ -63,7 +68,7 @@ export default function transformer(file, api) {});// 2. Remove size type imports (XDSStatusDotSize, XDSProgressBarSize)- root.find(j.ImportDeclaration).forEach((path) => {+ root.find(j.ImportDeclaration).forEach((/** @type {any} */ path) => {const specifiers = path.node.specifiers;if (!specifiers) return;diff --git a/packages/cli/src/codemods/transforms/v0.0.12/add-is-icon-only.mjs b/packages/cli/src/codemods/transforms/v0.0.12/add-is-icon-only.mjsindex c609790d7f..960f4bedf7 100644--- a/packages/cli/src/codemods/transforms/v0.0.12/add-is-icon-only.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.12/add-is-icon-only.mjs@@ -50,6 +50,11 @@ export const meta = {pr: '#1321',};+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);@@ -61,7 +66,7 @@ export default function transformer(file, api) {// Uses direct body manipulation instead of jscodeshift's insertAfter(),// which has a known bug that corrupts 'use client' directives into// double semicolons ('use client';;).- function insertAfterInBody(targetPath, newNode) {+ function insertAfterInBody(/** @type {any} */ targetPath, /** @type {any} */ newNode) {const body = root.get().node.program.body;const targetIndex = body.indexOf(targetPath.node);if (targetIndex !== -1) {@@ -69,14 +74,14 @@ export default function transformer(file, api) {} else {// Fallback: insert after all importsconst lastImportIdx = body.findLastIndex(- (n) => n.type === 'ImportDeclaration',+ (/** @type {any} */ n) => n.type === 'ImportDeclaration',);body.splice(lastImportIdx + 1, 0, newNode);}}// ---- 1. JSX elements: convert icon-only XDSButton to XDSIconButton ----- root.find(j.JSXOpeningElement).forEach((path) => {+ root.find(j.JSXOpeningElement).forEach((/** @type {any} */ path) => {const name = path.node.name;const componentName =name.type === 'JSXIdentifier' ? name.name : null;@@ -85,13 +90,13 @@ export default function transformer(file, api) {const attrs = path.node.attributes;const hasIcon = attrs.some(- (a) => a.type === 'JSXAttribute' && a.name?.name === 'icon',+ (/** @type {any} */ a) => a.type === 'JSXAttribute' && a.name?.name === 'icon',);const hasChildren = attrs.some(- (a) => a.type === 'JSXAttribute' && a.name?.name === 'children',+ (/** @type {any} */ a) => a.type === 'JSXAttribute' && a.name?.name === 'children',);const hasIsIconOnly = attrs.some(- (a) => a.type === 'JSXAttribute' && a.name?.name === 'isIconOnly',+ (/** @type {any} */ a) => a.type === 'JSXAttribute' && a.name?.name === 'isIconOnly',);if (!hasIcon || hasChildren || hasIsIconOnly) return;@@ -101,7 +106,7 @@ export default function transformer(file, api) {const hasJSXChildren =parent.type === 'JSXElement' &&parent.children &&- parent.children.some((child) => {+ parent.children.some((/** @type {any} */ child) => {if (child.type === 'JSXText') return child.value.trim() !== '';return true;});@@ -128,7 +133,7 @@ export default function transformer(file, api) {});// ---- 2. Remove redundant children that match label ----- root.find(j.JSXElement).forEach((path) => {+ root.find(j.JSXElement).forEach((/** @type {any} */ path) => {const opening = path.node.openingElement;const name = opening.name;const componentName =@@ -137,13 +142,13 @@ export default function transformer(file, api) {const attrs = opening.attributes;const hasIcon = attrs.some(- (a) => a.type === 'JSXAttribute' && a.name?.name === 'icon',+ (/** @type {any} */ a) => a.type === 'JSXAttribute' && a.name?.name === 'icon',);if (!hasIcon) return;// Get label valueconst labelAttr = attrs.find(- (a) => a.type === 'JSXAttribute' && a.name?.name === 'label',+ (/** @type {any} */ a) => a.type === 'JSXAttribute' && a.name?.name === 'label',);if (!labelAttr || !labelAttr.value) return;@@ -177,7 +182,7 @@ export default function transformer(file, api) {});// ---- 3. Object literals: add isIconOnly to button config objects ----- root.find(j.JSXOpeningElement).forEach((path) => {+ root.find(j.JSXOpeningElement).forEach((/** @type {any} */ path) => {const name = path.node.name;const componentName =name.type === 'JSXIdentifier' ? name.name : null;@@ -185,7 +190,7 @@ export default function transformer(file, api) {const attrs = path.node.attributes;const buttonAttr = attrs.find(- (a) =>+ (/** @type {any} */ a) =>a.type === 'JSXAttribute' &&a.name?.name === 'button' &&a.value?.type === 'JSXExpressionContainer' &&@@ -197,13 +202,13 @@ export default function transformer(file, api) {const props = obj.properties;const hasIcon = props.some(- (p) => (p.type === 'Property' || p.type === 'ObjectProperty') && p.key?.name === 'icon',+ (/** @type {any} */ p) => (p.type === 'Property' || p.type === 'ObjectProperty') && p.key?.name === 'icon',);const hasChildren = props.some(- (p) => (p.type === 'Property' || p.type === 'ObjectProperty') && p.key?.name === 'children',+ (/** @type {any} */ p) => (p.type === 'Property' || p.type === 'ObjectProperty') && p.key?.name === 'children',);const hasIsIconOnly = props.some(- (p) => (p.type === 'Property' || p.type === 'ObjectProperty') && p.key?.name === 'isIconOnly',+ (/** @type {any} */ p) => (p.type === 'Property' || p.type === 'ObjectProperty') && p.key?.name === 'isIconOnly',);if (hasIcon && !hasChildren && !hasIsIconOnly) {@@ -222,7 +227,7 @@ export default function transformer(file, api) {hasRemainingXDSButton = true;});// Also check for XDSButton in type annotations (e.g. typeof XDSButton)- root.find(j.Identifier, {name: 'XDSButton'}).forEach((path) => {+ root.find(j.Identifier, {name: 'XDSButton'}).forEach((/** @type {any} */ path) => {// Skip JSX identifiers (already counted above) and import specifiersif (path.parent.node.type === 'JSXOpeningElement' ||path.parent.node.type === 'JSXClosingElement' ||@@ -232,9 +237,9 @@ export default function transformer(file, api) {if (needsIconButtonImport) {let alreadyImported = false;- root.find(j.ImportDeclaration).forEach((path) => {+ root.find(j.ImportDeclaration).forEach((/** @type {any} */ path) => {if (path.node.specifiers.some(- (s) => s.type === 'ImportSpecifier' && s.imported.name === 'XDSIconButton',+ (/** @type {any} */ s) => s.type === 'ImportSpecifier' && s.imported.name === 'XDSIconButton',)) {alreadyImported = true;}@@ -244,13 +249,13 @@ export default function transformer(file, api) {// Handle @xds/core/Button import — may need splitting if it has// other specifiers (type imports, other components)if (!hasRemainingXDSButton) {- root.find(j.ImportDeclaration).forEach((path) => {+ root.find(j.ImportDeclaration).forEach((/** @type {any} */ path) => {if (alreadyImported) return;const source = path.node.source.value;if (source !== '@xds/core/Button') return;const specs = path.node.specifiers;const btnIdx = specs.findIndex(- (s) => s.type === 'ImportSpecifier' && s.imported.name === 'XDSButton',+ (/** @type {any} */ s) => s.type === 'ImportSpecifier' && s.imported.name === 'XDSButton',);if (btnIdx === -1) return;@@ -276,7 +281,7 @@ export default function transformer(file, api) {// For barrel imports, add the specifierif (!alreadyImported) {- root.find(j.ImportDeclaration).forEach((path) => {+ root.find(j.ImportDeclaration).forEach((/** @type {any} */ path) => {if (alreadyImported) return;if (path.node.source.value === '@xds/core') {path.node.specifiers.push(@@ -296,7 +301,7 @@ export default function transformer(file, api) {const xdsImports = root.find(j.ImportDeclaration)- .filter((p) => p.node.source.value.startsWith('@xds/'));+ .filter((/** @type {any} */ p) => p.node.source.value.startsWith('@xds/'));if (xdsImports.length > 0) {insertAfterInBody(xdsImports.at(-1), newImport);diff --git a/packages/cli/src/codemods/transforms/v0.0.13/icon-name-deprecations.mjs b/packages/cli/src/codemods/transforms/v0.0.13/icon-name-deprecations.mjsindex a17b49f35a..33a3185539 100644--- a/packages/cli/src/codemods/transforms/v0.0.13/icon-name-deprecations.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.13/icon-name-deprecations.mjs@@ -23,6 +23,7 @@ export const meta = {pr: '#1503',};+/** @type {Record<string, string>} */const RENAMES = {checkCircle: 'success',xCircle: 'error',@@ -31,13 +32,18 @@ const RENAMES = {/** Prop names that accept XDSIconName values */const ICON_PROPS = new Set(['icon', 'name', 'selectedIcon']);+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);let hasChanges = false;// Helper: rename a string literal node if it matches a deprecated name- function renameStringLiteral(node) {+ function renameStringLiteral(/** @type {any} */ node) {if (!node) return false;if (node.type === 'StringLiteral' || node.type === 'Literal') {const newName = RENAMES[node.value];@@ -51,7 +57,8 @@ export default function transformer(file, api) {}// Helper: recursively rename deprecated icon strings inside an expression- function renameInExpression(node) {+ /** @returns {boolean} */+ function renameInExpression(/** @type {any} */ node) {if (!node) return false;let changed = false;if (node.type === 'StringLiteral' || node.type === 'Literal') {@@ -67,7 +74,7 @@ export default function transformer(file, api) {}// 1. JSX attributes: icon="checkCircle" or icon={cond ? 'checkCircle' : 'copy'}- root.find(j.JSXAttribute).forEach((path) => {+ root.find(j.JSXAttribute).forEach((/** @type {any} */ path) => {const attrName = path.node.name?.name;if (!ICON_PROPS.has(attrName)) return;@@ -92,7 +99,7 @@ export default function transformer(file, api) {if (looksLikeIconRegistry) {const PropertyType = j.ObjectProperty ?? j.Property;- root.find(PropertyType).forEach((path) => {+ root.find(PropertyType).forEach((/** @type {any} */ path) => {const key = path.node.key;if (!key) return;const keyName =@@ -110,7 +117,7 @@ export default function transformer(file, api) {// 3. String literals in objects with icon-related keys// e.g. { label: "TestX", href: "/pages/testx", icon: "checkCircle" }const PropertyType2 = j.ObjectProperty ?? j.Property;- root.find(PropertyType2).forEach((path) => {+ root.find(PropertyType2).forEach((/** @type {any} */ path) => {const key = path.node.key;const keyName = key?.type === 'Identifier' ? key.name : key?.value;if (!ICON_PROPS.has(keyName)) return;diff --git a/packages/cli/src/codemods/transforms/v0.0.13/rename-attachments-to-drawer.mjs b/packages/cli/src/codemods/transforms/v0.0.13/rename-attachments-to-drawer.mjsindex 578a93d46e..be7f9e5eeb 100644--- a/packages/cli/src/codemods/transforms/v0.0.13/rename-attachments-to-drawer.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.13/rename-attachments-to-drawer.mjs@@ -22,15 +22,22 @@ export const meta = {pr: '#1714',};+/** @type {Record<string, string>} */const IMPORT_RENAMES = {XDSChatComposerAttachments: 'XDSChatComposerDrawer',XDSChatComposerAttachmentsProps: 'XDSChatComposerDrawerProps',};+/** @type {Record<string, string>} */const CSS_CLASS_RENAMES = {'xds-chat-composer-attachments': 'xds-chat-composer-drawer',};+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);@@ -40,7 +47,7 @@ export default function transformer(file, api) {const localToComponent = new Map();// --- 1. Rename imports ---- root.find(j.ImportSpecifier).forEach((path) => {+ root.find(j.ImportSpecifier).forEach((/** @type {any} */ path) => {const importedName = path.node.imported.name;const newName = IMPORT_RENAMES[importedName];if (!newName) return;@@ -66,7 +73,7 @@ export default function transformer(file, api) {root.find(j.JSXIdentifier, {name: oldName})- .forEach((path) => {+ .forEach((/** @type {any} */ path) => {const parent = path.parent.node;if (parent.type === 'JSXOpeningElement' ||@@ -79,7 +86,7 @@ export default function transformer(file, api) {}// --- 3. Rename `attachments` prop → `drawer` on XDSChatComposer ---- root.find(j.JSXOpeningElement).forEach((path) => {+ root.find(j.JSXOpeningElement).forEach((/** @type {any} */ path) => {const name = path.node.name;const componentName = name.type === 'JSXIdentifier' ? name.name : null;if (componentName !== 'XDSChatComposer') return;@@ -97,7 +104,7 @@ export default function transformer(file, api) {});// --- 4. Rename type references ---- root.find(j.TSTypeReference).forEach((path) => {+ root.find(j.TSTypeReference).forEach((/** @type {any} */ path) => {const typeName = path.node.typeName;if (typeName.type === 'Identifier') {const newName = IMPORT_RENAMES[typeName.name];@@ -109,7 +116,7 @@ export default function transformer(file, api) {});// Also handle plain Identifier references (e.g. typeof, React.ComponentProps<typeof X>)- root.find(j.Identifier, {name: 'XDSChatComposerAttachments'}).forEach((path) => {+ root.find(j.Identifier, {name: 'XDSChatComposerAttachments'}).forEach((/** @type {any} */ path) => {const parent = path.parent.node;if (parent.type === 'ImportSpecifier' ||@@ -122,7 +129,7 @@ export default function transformer(file, api) {hasChanges = true;});- root.find(j.Identifier, {name: 'XDSChatComposerAttachmentsProps'}).forEach((path) => {+ root.find(j.Identifier, {name: 'XDSChatComposerAttachmentsProps'}).forEach((/** @type {any} */ path) => {const parent = path.parent.node;if (parent.type === 'ImportSpecifier') return;path.node.name = 'XDSChatComposerDrawerProps';@@ -130,7 +137,7 @@ export default function transformer(file, api) {});// --- 5. Rename CSS class strings ---- root.find(j.StringLiteral).forEach((path) => {+ root.find(j.StringLiteral).forEach((/** @type {any} */ path) => {for (const [oldClass, newClass] of Object.entries(CSS_CLASS_RENAMES)) {if (path.node.value.includes(oldClass)) {path.node.value = path.node.value.replace(@@ -143,7 +150,7 @@ export default function transformer(file, api) {});// Also check template literals- root.find(j.TemplateLiteral).forEach((path) => {+ root.find(j.TemplateLiteral).forEach((/** @type {any} */ path) => {for (const quasi of path.node.quasis) {for (const [oldClass, newClass] of Object.entries(CSS_CLASS_RENAMES)) {if (quasi.value.raw.includes(oldClass)) {diff --git a/packages/cli/src/codemods/transforms/v0.0.13/toolbar-density-to-size.mjs b/packages/cli/src/codemods/transforms/v0.0.13/toolbar-density-to-size.mjsindex f6d388e902..2065c6b81e 100644--- a/packages/cli/src/codemods/transforms/v0.0.13/toolbar-density-to-size.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.13/toolbar-density-to-size.mjs@@ -24,17 +24,23 @@ export const meta = {};/** Map from old density values to new size values (null = remove prop). */+/** @type {Record<string, string | null>} */const DENSITY_TO_SIZE = {compact: 'sm',default: null, // md is the default, no prop needed};+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);let hasChanges = false;- root.find(j.JSXOpeningElement).forEach((path) => {+ root.find(j.JSXOpeningElement).forEach((/** @type {any} */ path) => {const name = path.node.name;const componentName =name.type === 'JSXIdentifier' ? name.name : null;@@ -42,7 +48,7 @@ export default function transformer(file, api) {const attrs = path.node.attributes;const densityIdx = attrs.findIndex(- (a) => a.type === 'JSXAttribute' && a.name?.name === 'density',+ (/** @type {any} */ a) => a.type === 'JSXAttribute' && a.name?.name === 'density',);if (densityIdx === -1) return;@@ -106,7 +112,7 @@ export default function transformer(file, api) {if (importsToolbar) {// jscodeshift uses Property (default parser) or ObjectProperty (babel/tsx parser)const PropertyType = j.ObjectProperty ?? j.Property;- root.find(PropertyType, {key: {name: 'density'}}).forEach((path) => {+ root.find(PropertyType, {key: {name: 'density'}}).forEach((/** @type {any} */ path) => {const value = path.node.value;// args: { density: 'compact' } → args: { size: 'sm' }@@ -140,7 +146,7 @@ export default function transformer(file, api) {path.node.key = j.identifier('size');// Update options array if presentconst optionsProp = value.properties.find(- (p) => p.key?.name === 'options',+ (/** @type {any} */ p) => p.key?.name === 'options',);if (optionsProp && optionsProp.value.type === 'ArrayExpression') {optionsProp.value = j.arrayExpression([diff --git a/packages/cli/src/codemods/transforms/v0.0.14/rename-action-props.mjs b/packages/cli/src/codemods/transforms/v0.0.14/rename-action-props.mjsindex b5806e1012..74f0d52e15 100644--- a/packages/cli/src/codemods/transforms/v0.0.14/rename-action-props.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.14/rename-action-props.mjs@@ -30,6 +30,7 @@ export const meta = {* Map of old prop names → new prop names.* Ordered longest-first to avoid partial matches during iteration.*/+/** @type {Record<string, string>} */const PROP_RENAMES = {onPressedChangeAction: 'pressedChangeAction',onScrollToTopAction: 'scrollToTopAction',@@ -37,13 +38,18 @@ const PROP_RENAMES = {onClickAction: 'clickAction',};+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);let hasChanges = false;// --- 1. Rename JSX attributes ---- root.find(j.JSXAttribute).forEach((path) => {+ root.find(j.JSXAttribute).forEach((/** @type {any} */ path) => {const name = path.node.name;if (name.type !== 'JSXIdentifier') return;@@ -59,7 +65,7 @@ export default function transformer(file, api) {// Must run before step 3 so the ObjectPattern keys are renamed first and tracked.const renamedBindings = new Map(); // oldLocalName → newLocalName- root.find(j.ObjectPattern).forEach((path) => {+ root.find(j.ObjectPattern).forEach((/** @type {any} */ path) => {for (const prop of path.node.properties) {if (prop.type !== 'ObjectProperty') continue;const key = prop.key;@@ -97,7 +103,7 @@ export default function transformer(file, api) {// --- 3. Rename object property keys (e.g. { onChangeAction: fn }) ---// Covers cases like useXDSImperativeAlertDialog({ onAction: ... })// Skips ObjectProperty inside ObjectPattern (already handled in step 2).- root.find(j.ObjectProperty).forEach((path) => {+ root.find(j.ObjectProperty).forEach((/** @type {any} */ path) => {// Skip if inside a destructuring patternif (path.parent.node.type === 'ObjectPattern') return;@@ -121,7 +127,7 @@ export default function transformer(file, api) {// --- 4. Rename interface/type property signatures ---// Covers: interface Props { onChangeAction?: ... } → { changeAction?: ... }- root.find(j.TSPropertySignature).forEach((path) => {+ root.find(j.TSPropertySignature).forEach((/** @type {any} */ path) => {const key = path.node.key;if (key.type === 'Identifier') {const newName = PROP_RENAMES[key.name];@@ -136,7 +142,7 @@ export default function transformer(file, api) {// When { onChangeAction } was renamed to { changeAction }, all references// to the local variable `onChangeAction` must become `changeAction`.if (renamedBindings.size > 0) {- root.find(j.Identifier).forEach((path) => {+ root.find(j.Identifier).forEach((/** @type {any} */ path) => {const newName = renamedBindings.get(path.node.name);if (!newName) return;diff --git a/packages/cli/src/codemods/transforms/v0.0.14/rename-section-wash-to-muted.mjs b/packages/cli/src/codemods/transforms/v0.0.14/rename-section-wash-to-muted.mjsindex 3be618eb85..2eb18a0f16 100644--- a/packages/cli/src/codemods/transforms/v0.0.14/rename-section-wash-to-muted.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.14/rename-section-wash-to-muted.mjs@@ -26,6 +26,11 @@ export const meta = {/** Components affected by this rename. */const TARGET_COMPONENTS = new Set(['XDSSection', 'XDSToolbar']);+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);@@ -33,12 +38,12 @@ export default function transformer(file, api) {// 1. Rename JSX attribute value: variant="wash" → variant="muted"// Only on XDSSection and XDSToolbar.- root.find(j.JSXOpeningElement).forEach((path) => {+ root.find(j.JSXOpeningElement).forEach((/** @type {any} */ path) => {const name = path.node.name;const componentName = name.type === 'JSXIdentifier' ? name.name : null;if (!componentName || !TARGET_COMPONENTS.has(componentName)) return;- path.node.attributes.forEach((attr) => {+ path.node.attributes.forEach((/** @type {any} */ attr) => {if (attr.type !== 'JSXAttribute') return;if (attr.name.name !== 'variant') return;@@ -79,7 +84,7 @@ export default function transformer(file, api) {if (importsTarget) {const PropertyType = j.ObjectProperty ?? j.Property;- root.find(PropertyType, {key: {name: 'variant'}}).forEach((path) => {+ root.find(PropertyType, {key: {name: 'variant'}}).forEach((/** @type {any} */ path) => {const value = path.node.value;// variant: 'wash' → variant: 'muted'@@ -95,10 +100,10 @@ export default function transformer(file, api) {// variant: { options: ['...', 'wash', '...'] } → replace 'wash' with 'muted'if (value.type === 'ObjectExpression') {const optionsProp = value.properties.find(- (p) => p.key && p.key.name === 'options',+ (/** @type {any} */ p) => p.key && p.key.name === 'options',);if (optionsProp && optionsProp.value.type === 'ArrayExpression') {- optionsProp.value.elements.forEach((el) => {+ optionsProp.value.elements.forEach((/** @type {any} */ el) => {if (el &&(el.type === 'StringLiteral' || el.type === 'Literal') &&@@ -117,7 +122,7 @@ export default function transformer(file, api) {// 3. JSX text children: replace "wash" text content adjacent to target components.// Covers labels like <h4>wash</h4> that describe the variant in Storybook stories.if (importsTarget) {- root.find(j.JSXText).forEach((path) => {+ root.find(j.JSXText).forEach((/** @type {any} */ path) => {if (path.node.value.trim() === 'wash') {path.node.value = path.node.value.replace('wash', 'muted');if (path.node.raw) path.node.raw = path.node.raw.replace('wash', 'muted');diff --git a/packages/cli/src/codemods/transforms/v0.0.14/rename-status-variants.mjs b/packages/cli/src/codemods/transforms/v0.0.14/rename-status-variants.mjsindex 98138c6b4c..c338985dbc 100644--- a/packages/cli/src/codemods/transforms/v0.0.14/rename-status-variants.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.14/rename-status-variants.mjs@@ -77,7 +77,7 @@ for (const props of COMPONENT_PROPS.values()) {* Check if a key matches a target prop — exact or case-insensitive suffix.* e.g. "dotVariant" matches because it ends with "variant".*/-function matchesPropName(keyName) {+function matchesPropName(/** @type {any} */ keyName) {if (TARGET_PROP_NAMES.has(keyName)) return true;const lower = keyName.toLowerCase();for (const prop of TARGET_PROP_NAMES) {@@ -86,6 +86,11 @@ function matchesPropName(keyName) {return false;}+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);@@ -96,7 +101,7 @@ export default function transformer(file, api) {* Unwraps TSAsExpression (e.g. 'positive' as const) to reach the literal.* @returns {boolean} whether a rename occurred*/- function renameValue(node, {precise = false} = {}) {+ function renameValue(/** @type {any} */ node, {precise = false} = {}) {if (!node) return false;// Unwrap TSAsExpression (e.g. 'positive' as const → StringLiteral)@@ -123,11 +128,11 @@ export default function transformer(file, api) {/*** Rename elements in an array (handles TSAsExpression wrapping).*/- function renameArrayElements(node, {precise = false} = {}) {+ function renameArrayElements(/** @type {any} */ node, {precise = false} = {}) {let arrayNode = node;if (arrayNode.type === 'TSAsExpression') arrayNode = arrayNode.expression;if (arrayNode.type !== 'ArrayExpression') return;- arrayNode.elements.forEach((el) => {+ arrayNode.elements.forEach((/** @type {any} */ el) => {if (renameValue(el, {precise})) hasChanges = true;});}@@ -139,7 +144,7 @@ export default function transformer(file, api) {);// 1. JSX attributes on target components- root.find(j.JSXOpeningElement).forEach((path) => {+ root.find(j.JSXOpeningElement).forEach((/** @type {any} */ path) => {const name = path.node.name;const componentName = name.type === 'JSXIdentifier' ? name.name : null;if (!componentName) return;@@ -148,14 +153,14 @@ export default function transformer(file, api) {// For non-target components, only check suffixed props if file imports targetsif (!isDirectTarget && !importsTarget) return;- path.node.attributes.forEach((attr) => {+ path.node.attributes.forEach((/** @type {any} */ attr) => {if (attr.type !== 'JSXAttribute') return;const attrName = attr.name.name;if (isDirectTarget) {// Direct targets: only their specific propsconst targetProps = COMPONENT_PROPS.get(componentName);- if (!targetProps.has(attrName)) return;+ if (!targetProps || !targetProps.has(attrName)) return;} else {// Non-target components: suffixed prop names only// (e.g. dotVariant on ChangelogSection wrapping XDSStatusDot)@@ -201,7 +206,7 @@ export default function transformer(file, api) {// Handles args objects, config objects, Storybook argTypes, etc.if (importsTarget) {const PropertyType = j.ObjectProperty ?? j.Property;- root.find(PropertyType).forEach((path) => {+ root.find(PropertyType).forEach((/** @type {any} */ path) => {const key = path.node.key;const keyName =key.type === 'Identifier'@@ -223,7 +228,7 @@ export default function transformer(file, api) {// variant: { options: ['positive', 'negative', ...] }if (value.type === 'ObjectExpression') {const optionsProp = value.properties.find(- (p) => p.key && (p.key.name === 'options' || p.key.value === 'options'),+ (/** @type {any} */ p) => p.key && (p.key.name === 'options' || p.key.value === 'options'),);if (optionsProp) {renameArrayElements(optionsProp.value);@@ -237,7 +242,7 @@ export default function transformer(file, api) {// 3. TypeScript type references: 'positive' | 'negative' in union typesif (importsTarget) {- root.find(j.TSLiteralType).forEach((path) => {+ root.find(j.TSLiteralType).forEach((/** @type {any} */ path) => {const lit = path.node.literal;if (renameValue(lit)) hasChanges = true;});diff --git a/packages/cli/src/codemods/transforms/v0.0.15/migrate-item-children-to-endcontent.mjs b/packages/cli/src/codemods/transforms/v0.0.15/migrate-item-children-to-endcontent.mjsindex cb380f42ed..868df1c308 100644--- a/packages/cli/src/codemods/transforms/v0.0.15/migrate-item-children-to-endcontent.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.15/migrate-item-children-to-endcontent.mjs@@ -30,24 +30,24 @@ export const meta = {'Moves trailing content on `XDSDropdownMenuItem`, `XDSContextMenuItem`, and `XDSSelectorOption` from deprecated `children` usage to the `endContent` prop.',};-function isWhitespaceText(node) {+function isWhitespaceText(/** @type {any} */ node) {return node.type === 'JSXText' && node.value.trim() === '';}-function isEmptyExpression(node) {+function isEmptyExpression(/** @type {any} */ node) {return (node.type === 'JSXExpressionContainer' &&node.expression.type === 'JSXEmptyExpression');}-function getMeaningfulChildren(children) {+function getMeaningfulChildren(/** @type {any} */ children) {return children.filter(- child => !isWhitespaceText(child) && !isEmptyExpression(child),+ (/** @type {any} */ child) => !isWhitespaceText(child) && !isEmptyExpression(child),);}-function createEndContentValue(j, children) {+function createEndContentValue(/** @type {any} */ j, /** @type {any} */ children) {if (children.length === 0) {return null;}@@ -74,18 +74,23 @@ function createEndContentValue(j, children) {);}-function getJSXAttribute(openingElement, name) {+function getJSXAttribute(/** @type {any} */ openingElement, /** @type {any} */ name) {return openingElement.attributes.find(- attr => attr.type === 'JSXAttribute' && attr.name.name === name,+ (/** @type {any} */ attr) => attr.type === 'JSXAttribute' && attr.name.name === name,);}+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);let hasChanges = false;- root.find(j.JSXElement).forEach(path => {+ root.find(j.JSXElement).forEach((/** @type {any} */ path) => {const elementName = path.node.openingElement.name;if (elementName.type !== 'JSXIdentifier' ||diff --git a/packages/cli/src/codemods/transforms/v0.0.15/migrate-selector-children-to-render-option.mjs b/packages/cli/src/codemods/transforms/v0.0.15/migrate-selector-children-to-render-option.mjsindex 1f2821b753..a0c8c0a1ab 100644--- a/packages/cli/src/codemods/transforms/v0.0.15/migrate-selector-children-to-render-option.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.15/migrate-selector-children-to-render-option.mjs@@ -27,7 +27,7 @@ export const meta = {const COMPONENTS = new Set(['XDSSelector', 'XDSMultiSelector']);-function isXDSCoreSource(source) {+function isXDSCoreSource(/** @type {any} */ source) {return (source === '@xds/core' ||source === '@xds/core/Selector' ||@@ -35,7 +35,7 @@ function isXDSCoreSource(source) {);}-function sourceCanImport(source, importedName) {+function sourceCanImport(/** @type {any} */ source, /** @type {any} */ importedName) {if (source === '@xds/core') {return COMPONENTS.has(importedName);}@@ -48,11 +48,11 @@ function sourceCanImport(source, importedName) {return false;}-function collectSelectorNames(root, j) {+function collectSelectorNames(/** @type {any} */ root, /** @type {any} */ j) {const localNames = new Map();const namespaceNames = new Set();- root.find(j.ImportDeclaration).forEach(path => {+ root.find(j.ImportDeclaration).forEach((/** @type {any} */ path) => {const source = path.node.source.value;if (typeof source !== 'string' || !isXDSCoreSource(source)) {return;@@ -80,7 +80,7 @@ function collectSelectorNames(root, j) {return {localNames, namespaceNames};}-function getComponentName(name, localNames, namespaceNames) {+function getComponentName(/** @type {any} */ name, /** @type {any} */ localNames, /** @type {any} */ namespaceNames) {if (name.type === 'JSXIdentifier') {return localNames.get(name.name) ?? null;}@@ -98,24 +98,24 @@ function getComponentName(name, localNames, namespaceNames) {return null;}-function isWhitespaceText(node) {+function isWhitespaceText(/** @type {any} */ node) {return node.type === 'JSXText' && node.value.trim() === '';}-function isEmptyExpression(node) {+function isEmptyExpression(/** @type {any} */ node) {return (node.type === 'JSXExpressionContainer' &&node.expression.type === 'JSXEmptyExpression');}-function getMeaningfulChildren(children) {+function getMeaningfulChildren(/** @type {any} */ children) {return children.filter(- child => !isWhitespaceText(child) && !isEmptyExpression(child),+ (/** @type {any} */ child) => !isWhitespaceText(child) && !isEmptyExpression(child),);}-function isRenderableExpression(expression) {+function isRenderableExpression(/** @type {any} */ expression) {return (expression.type === 'ArrowFunctionExpression' ||expression.type === 'FunctionExpression' ||@@ -124,12 +124,17 @@ function isRenderableExpression(expression) {);}-function getJSXAttribute(openingElement, name) {+function getJSXAttribute(/** @type {any} */ openingElement, /** @type {any} */ name) {return openingElement.attributes.find(- attr => attr.type === 'JSXAttribute' && attr.name.name === name,+ (/** @type {any} */ attr) => attr.type === 'JSXAttribute' && attr.name.name === name,);}+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);@@ -140,7 +145,7 @@ export default function transformer(file, api) {return undefined;}- root.find(j.JSXElement).forEach(path => {+ root.find(j.JSXElement).forEach((/** @type {any} */ path) => {const componentName = getComponentName(path.node.openingElement.name,localNames,diff --git a/packages/cli/src/codemods/transforms/v0.0.15/migrate-theme-selectors-to-data-attrs.mjs b/packages/cli/src/codemods/transforms/v0.0.15/migrate-theme-selectors-to-data-attrs.mjsindex 282f1fc73a..1a7bf5e9e3 100644--- a/packages/cli/src/codemods/transforms/v0.0.15/migrate-theme-selectors-to-data-attrs.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.15/migrate-theme-selectors-to-data-attrs.mjs@@ -104,11 +104,11 @@ const SECTION_VARIANTS = new Set(['section', 'transparent', 'muted']);const DIVIDER_VARIANTS = new Set(['subtle', 'strong']);const ORIENTATIONS = new Set(['horizontal', 'vertical']);-function attr(name, value) {+function attr(/** @type {any} */ name, /** @type {any} */ value) {return `[data-${name}="${value}"]`;}-function valueToAttr(component, value) {+function valueToAttr(/** @type {any} */ component, /** @type {any} */ value) {// Numeric-prefixed classes emitted as prop-value (level-2, gap-4, cols-3).let match = value.match(/^level-(\d+)$/);if (match) return attr('level', match[1]);@@ -211,8 +211,8 @@ function valueToAttr(component, value) {const SELECTOR_RE = /\.((?:xds-[a-z0-9-]+))(\.(?:-?[_a-zA-Z][_a-zA-Z0-9-]*))+/g;-export function migrateThemeSelectors(source) {- return source.replace(SELECTOR_RE, (full, component) => {+export function migrateThemeSelectors(/** @type {any} */ source) {+ return source.replace(SELECTOR_RE, (/** @type {any} */ full, /** @type {any} */ component) => {const classChain = full.slice(component.length + 1);const values = classChain.split('.').filter(Boolean);@@ -229,6 +229,10 @@ export function migrateThemeSelectors(source) {});}+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @returns {string | null | undefined}+ */export default function transformer(file) {const result = migrateThemeSelectors(file.source);return result === file.source ? undefined : result;diff --git a/packages/cli/src/codemods/transforms/v0.0.15/rename-date-picker-to-input.mjs b/packages/cli/src/codemods/transforms/v0.0.15/rename-date-picker-to-input.mjsindex 261f1e9d9e..1f2030d796 100644--- a/packages/cli/src/codemods/transforms/v0.0.15/rename-date-picker-to-input.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.15/rename-date-picker-to-input.mjs@@ -45,13 +45,18 @@ const IDENTIFIER_RENAMES = new Map([['XDSDateRangePickerStatusType', 'XDSDateRangeInputStatusType'],]);+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);let hasChanges = false;// 1. Rename import/export source paths- root.find(j.ImportDeclaration).forEach((path) => {+ root.find(j.ImportDeclaration).forEach((/** @type {any} */ path) => {const source = path.node.source.value;const renamed = IMPORT_PATH_RENAMES.get(source);if (renamed) {@@ -60,7 +65,7 @@ export default function transformer(file, api) {}});- root.find(j.ExportNamedDeclaration).forEach((path) => {+ root.find(j.ExportNamedDeclaration).forEach((/** @type {any} */ path) => {if (path.node.source) {const source = path.node.source.value;const renamed = IMPORT_PATH_RENAMES.get(source);@@ -72,7 +77,7 @@ export default function transformer(file, api) {});// 2. Rename all identifiers (covers imports, type refs, variable names)- root.find(j.Identifier).forEach((path) => {+ root.find(j.Identifier).forEach((/** @type {any} */ path) => {const renamed = IDENTIFIER_RENAMES.get(path.node.name);if (renamed) {path.node.name = renamed;@@ -81,7 +86,7 @@ export default function transformer(file, api) {});// 3. Rename JSX element names- root.find(j.JSXIdentifier).forEach((path) => {+ root.find(j.JSXIdentifier).forEach((/** @type {any} */ path) => {const renamed = IDENTIFIER_RENAMES.get(path.node.name);if (renamed) {path.node.name = renamed;@@ -90,7 +95,7 @@ export default function transformer(file, api) {});// 4. Rename string literals (covers displayName assignments)- root.find(j.StringLiteral).forEach((path) => {+ root.find(j.StringLiteral).forEach((/** @type {any} */ path) => {const renamed = IDENTIFIER_RENAMES.get(path.node.value);if (renamed) {path.node.value = renamed;@@ -99,7 +104,7 @@ export default function transformer(file, api) {});// Also handle Literal nodes (parser-dependent)- root.find(j.Literal).forEach((path) => {+ root.find(j.Literal).forEach((/** @type {any} */ path) => {if (typeof path.node.value === 'string') {const renamed = IDENTIFIER_RENAMES.get(path.node.value);if (renamed) {diff --git a/packages/cli/src/codemods/transforms/v0.0.15/rename-imperative-ref-to-handleRef.mjs b/packages/cli/src/codemods/transforms/v0.0.15/rename-imperative-ref-to-handleRef.mjsindex d3214a0ee3..259a7e7a07 100644--- a/packages/cli/src/codemods/transforms/v0.0.15/rename-imperative-ref-to-handleRef.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.15/rename-imperative-ref-to-handleRef.mjs@@ -29,12 +29,17 @@ const IMPERATIVE_REF_COMPONENTS = new Set(['XDSChartStreamGL',]);+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);let hasChanges = false;- root.find(j.JSXOpeningElement).forEach(path => {+ root.find(j.JSXOpeningElement).forEach((/** @type {any} */ path) => {const name = path.node.name;const componentName = name.type === 'JSXIdentifier' ? name.name : null;if (componentName == null) return;diff --git a/packages/cli/src/codemods/transforms/v0.0.15/rename-isStreaming-to-isStopShown.mjs b/packages/cli/src/codemods/transforms/v0.0.15/rename-isStreaming-to-isStopShown.mjsindex 6e128694ce..00640f6767 100644--- a/packages/cli/src/codemods/transforms/v0.0.15/rename-isStreaming-to-isStopShown.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.15/rename-isStreaming-to-isStopShown.mjs@@ -26,13 +26,18 @@ export const meta = {const TARGET_COMPONENTS = new Set(['XDSChatComposer', 'XDSChatSendButton']);+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);let hasChanges = false;// Rename JSX prop on target components only- root.find(j.JSXOpeningElement).forEach((path) => {+ root.find(j.JSXOpeningElement).forEach((/** @type {any} */ path) => {const name = path.node.name;const componentName = name.type === 'JSXIdentifier' ? name.name : null;if (!TARGET_COMPONENTS.has(componentName)) return;diff --git a/packages/cli/src/codemods/transforms/v0.0.15/rename-stack-element-to-as.mjs b/packages/cli/src/codemods/transforms/v0.0.15/rename-stack-element-to-as.mjsindex 4e8d248019..f52fc24cbb 100644--- a/packages/cli/src/codemods/transforms/v0.0.15/rename-stack-element-to-as.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.15/rename-stack-element-to-as.mjs@@ -17,6 +17,11 @@ const TARGET_COMPONENTS = new Set(['XDSStackItem',]);+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);@@ -24,12 +29,12 @@ export default function transformer(file, api) {root.find(j.JSXOpeningElement)- .filter((path) => {+ .filter((/** @type {any} */ path) => {const name = path.node.name;return name.type === 'JSXIdentifier' && TARGET_COMPONENTS.has(name.name);})- .forEach((path) => {- path.node.attributes.forEach((attr) => {+ .forEach((/** @type {any} */ path) => {+ path.node.attributes.forEach((/** @type {any} */ attr) => {if (attr.type === 'JSXAttribute' && attr.name.name === 'element') {attr.name.name = 'as';hasChanges = true;diff --git a/packages/cli/src/codemods/transforms/v0.0.2/migrate-badge-dot-to-statusdot.mjs b/packages/cli/src/codemods/transforms/v0.0.2/migrate-badge-dot-to-statusdot.mjsindex 3376169e91..0f4e936a47 100644--- a/packages/cli/src/codemods/transforms/v0.0.2/migrate-badge-dot-to-statusdot.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.2/migrate-badge-dot-to-statusdot.mjs@@ -15,6 +15,7 @@ export const meta = {pr: '#945',};+/** @type {Record<string, string>} */const VARIANT_MAP = {success: 'positive',error: 'negative',@@ -23,12 +24,12 @@ const VARIANT_MAP = {neutral: 'neutral',};-function isDotMode(path) {+function isDotMode(/** @type {any} */ path) {const opening = path.node.openingElement;// Dot mode is indicated by shape="dot" propconst hasShapeDot = opening.attributes.some(- (attr) =>+ (/** @type {any} */ attr) =>attr.type === 'JSXAttribute' &&attr.name.type === 'JSXIdentifier' &&attr.name.name === 'shape' &&@@ -40,7 +41,7 @@ function isDotMode(path) {// If icon prop is present, leave aloneconst hasIcon = opening.attributes.some(- (attr) =>+ (/** @type {any} */ attr) =>attr.type === 'JSXAttribute' &&attr.name.type === 'JSXIdentifier' &&attr.name.name === 'icon',@@ -50,13 +51,18 @@ function isDotMode(path) {return true;}+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);let hasChanges = false;// Find all XDSBadge JSX elements- root.find(j.JSXElement).forEach((path) => {+ root.find(j.JSXElement).forEach((/** @type {any} */ path) => {const opening = path.node.openingElement;if (opening.name.type !== 'JSXIdentifier' ||@@ -69,11 +75,12 @@ export default function transformer(file, api) {// Map variantconst variantAttr = opening.attributes.find(- (attr) =>+ (/** @type {any} */ attr) =>attr.type === 'JSXAttribute' &&attr.name.name === 'variant',);+ /** @type {string | null} */let newVariantValue = 'neutral'; // defaultif (variantAttr) {if (@@ -140,7 +147,7 @@ export default function transformer(file, api) {if (!hasChanges) return undefined;// Handle imports- const badgeImports = root.find(j.ImportDeclaration).filter((path) => {+ const badgeImports = root.find(j.ImportDeclaration).filter((/** @type {any} */ path) => {const source = path.node.source.value;return (typeof source === 'string' &&@@ -165,7 +172,7 @@ export default function transformer(file, api) {root.find(j.ImportDefaultSpecifier).filter(- (path) => path.node.local.name === 'XDSStatusDot',+ (/** @type {any} */ path) => path.node.local.name === 'XDSStatusDot',).size() > 0;@@ -176,7 +183,7 @@ export default function transformer(file, api) {);// Insert after the last existing xds import, or at the top- const xdsImports = root.find(j.ImportDeclaration).filter((path) => {+ const xdsImports = root.find(j.ImportDeclaration).filter((/** @type {any} */ path) => {const source = path.node.source.value;return typeof source === 'string' && source.includes('@xds/core');});@@ -195,11 +202,11 @@ export default function transformer(file, api) {// Remove XDSBadge import if no remaining usagesif (remainingBadgeUsages === 0) {- badgeImports.forEach((path) => {+ badgeImports.forEach((/** @type {any} */ path) => {const specifiers = path.node.specifiers;if (!specifiers) return;- const filtered = specifiers.filter((s) => {+ const filtered = specifiers.filter((/** @type {any} */ s) => {if (s.type === 'ImportSpecifier' &&s.imported.type === 'Identifier' &&diff --git a/packages/cli/src/codemods/transforms/v0.0.2/migrate-gap-to-numeric.mjs b/packages/cli/src/codemods/transforms/v0.0.2/migrate-gap-to-numeric.mjsindex 41201770d4..b00bb9479a 100644--- a/packages/cli/src/codemods/transforms/v0.0.2/migrate-gap-to-numeric.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.2/migrate-gap-to-numeric.mjs@@ -23,6 +23,7 @@ export const meta = {/*** Mapping from string token to numeric value.*/+/** @type {Record<string, number>} */const TOKEN_TO_NUMBER = {space0: 0,'space0.5': 0.5,@@ -58,12 +59,17 @@ const XDS_LAYOUT_ELEMENTS = new Set(['XDSStackItem',]);+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);let hasChanges = false;- root.find(j.JSXOpeningElement).forEach((elementPath) => {+ root.find(j.JSXOpeningElement).forEach((/** @type {any} */ elementPath) => {const nameNode = elementPath.node.name;// Only handle simple identifier element names like <XDSStack>. Skip member// expressions (e.g. <Foo.Bar>) and namespaced names — they're never XDS.diff --git a/packages/cli/src/codemods/transforms/v0.0.2/migrate-isFullBleed-to-padding.mjs b/packages/cli/src/codemods/transforms/v0.0.2/migrate-isFullBleed-to-padding.mjsindex af72a3bb32..642f321523 100644--- a/packages/cli/src/codemods/transforms/v0.0.2/migrate-isFullBleed-to-padding.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.2/migrate-isFullBleed-to-padding.mjs@@ -29,6 +29,11 @@ const TARGET_COMPONENTS = ['XDSLayoutPanel',];+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);@@ -39,10 +44,10 @@ export default function transformer(file, api) {.find(j.JSXOpeningElement, {name: {name: componentName},})- .forEach((path) => {+ .forEach((/** @type {any} */ path) => {const attrs = path.node.attributes;const isFullBleedIndex = attrs.findIndex(- (attr) =>+ (/** @type {any} */ attr) =>attr.type === 'JSXAttribute' && attr.name.name === 'isFullBleed',);@@ -57,7 +62,7 @@ export default function transformer(file, api) {if (value === null) {attrs.splice(isFullBleedIndex, 1);const hasPadding = attrs.some(- (a) => a.type === 'JSXAttribute' && a.name.name === 'padding',+ (/** @type {any} */ a) => a.type === 'JSXAttribute' && a.name.name === 'padding',);if (!hasPadding) {attrs.push(@@ -82,7 +87,7 @@ export default function transformer(file, api) {// isFullBleed={true} → padding={0}attrs.splice(isFullBleedIndex, 1);const hasPadding = attrs.some(- (a) => a.type === 'JSXAttribute' && a.name.name === 'padding',+ (/** @type {any} */ a) => a.type === 'JSXAttribute' && a.name.name === 'padding',);if (!hasPadding) {attrs.push(diff --git a/packages/cli/src/codemods/transforms/v0.0.2/migrate-useXDSIcon-to-getIcon.mjs b/packages/cli/src/codemods/transforms/v0.0.2/migrate-useXDSIcon-to-getIcon.mjsindex 11d5397b20..65226c07ab 100644--- a/packages/cli/src/codemods/transforms/v0.0.2/migrate-useXDSIcon-to-getIcon.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.2/migrate-useXDSIcon-to-getIcon.mjs@@ -18,6 +18,11 @@ export const meta = {pr: '#531',};+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);@@ -28,13 +33,13 @@ export default function transformer(file, api) {.find(j.CallExpression, {callee: {type: 'Identifier', name: 'useXDSIcon'},})- .forEach((path) => {+ .forEach((/** @type {any} */ path) => {path.node.callee.name = 'getIcon';hasChanges = true;});// 2. Update import specifiers: useXDSIcon → getIcon- root.find(j.ImportSpecifier).forEach((path) => {+ root.find(j.ImportSpecifier).forEach((/** @type {any} */ path) => {const imported = path.node.imported;if (imported.type === 'Identifier' && imported.name === 'useXDSIcon') {const oldLocal = path.node.local ? path.node.local.name : null;@@ -48,11 +53,11 @@ export default function transformer(file, api) {});// 3. Remove IconRegistryContext from import specifiers- root.find(j.ImportDeclaration).forEach((path) => {+ root.find(j.ImportDeclaration).forEach((/** @type {any} */ path) => {const specifiers = path.node.specifiers;if (!specifiers) return;- const filtered = specifiers.filter((s) => {+ const filtered = specifiers.filter((/** @type {any} */ s) => {if (s.type === 'ImportSpecifier' &&s.imported.type === 'Identifier' &&@@ -73,7 +78,7 @@ export default function transformer(file, api) {});// 4. Update import source: '../Icon/IconRegistry' or similar → '../Icon/globalIconRegistry'- root.find(j.ImportDeclaration).forEach((path) => {+ root.find(j.ImportDeclaration).forEach((/** @type {any} */ path) => {const source = path.node.source.value;if (typeof source === 'string' && source.includes('IconRegistry') && !source.includes('globalIconRegistry')) {path.node.source.value = source.replace(@@ -85,7 +90,7 @@ export default function transformer(file, api) {});// 5. Remove <IconRegistryContext.Provider> wrappers — replace with children- root.find(j.JSXElement).forEach((path) => {+ root.find(j.JSXElement).forEach((/** @type {any} */ path) => {const opening = path.node.openingElement;if (opening.name.type === 'JSXMemberExpression' &&@@ -113,7 +118,7 @@ export default function transformer(file, api) {.find(j.VariableDeclarator, {init: {type: 'Identifier', name: 'IconRegistryContext'},})- .forEach((path) => {+ .forEach((/** @type {any} */ path) => {j(path.parent).remove();hasChanges = true;});diff --git a/packages/cli/src/codemods/transforms/v0.0.2/rename-banner-endButton-to-endContent.mjs b/packages/cli/src/codemods/transforms/v0.0.2/rename-banner-endButton-to-endContent.mjsindex 7007e2042c..8de6ae8082 100644--- a/packages/cli/src/codemods/transforms/v0.0.2/rename-banner-endButton-to-endContent.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.2/rename-banner-endButton-to-endContent.mjs@@ -11,6 +11,11 @@ export const meta = {pr: '#437',};+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);@@ -20,8 +25,8 @@ export default function transformer(file, api) {.find(j.JSXOpeningElement, {name: {name: 'XDSBanner'},})- .forEach((path) => {- path.node.attributes.forEach((attr) => {+ .forEach((/** @type {any} */ path) => {+ path.node.attributes.forEach((/** @type {any} */ attr) => {if (attr.type === 'JSXAttribute' && attr.name.name === 'endButton') {attr.name.name = 'endContent';hasChanges = true;diff --git a/packages/cli/src/codemods/transforms/v0.0.2/rename-form-tooltip-startIcon.mjs b/packages/cli/src/codemods/transforms/v0.0.2/rename-form-tooltip-startIcon.mjsindex 022ec22479..fabec4e11c 100644--- a/packages/cli/src/codemods/transforms/v0.0.2/rename-form-tooltip-startIcon.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.2/rename-form-tooltip-startIcon.mjs@@ -25,23 +25,29 @@ const FORM_COMPONENTS = new Set(['XDSTimeInput',]);+/** @type {Record<string, string>} */const PROP_RENAMES = {tooltip: 'labelTooltip',startIcon: 'labelIcon',};+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);let hasChanges = false;- root.find(j.JSXOpeningElement).forEach((path) => {+ root.find(j.JSXOpeningElement).forEach((/** @type {any} */ path) => {const name = path.node.name;if (name.type !== 'JSXIdentifier' || !FORM_COMPONENTS.has(name.name)) {return;}- path.node.attributes.forEach((attr) => {+ path.node.attributes.forEach((/** @type {any} */ attr) => {if (attr.type === 'JSXAttribute' && attr.name.name in PROP_RENAMES) {attr.name.name = PROP_RENAMES[attr.name.name];hasChanges = true;diff --git a/packages/cli/src/codemods/transforms/v0.0.2/rename-isShown-to-isOpen.mjs b/packages/cli/src/codemods/transforms/v0.0.2/rename-isShown-to-isOpen.mjsindex 8f5e43852f..9fed81c1c0 100644--- a/packages/cli/src/codemods/transforms/v0.0.2/rename-isShown-to-isOpen.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.2/rename-isShown-to-isOpen.mjs@@ -14,6 +14,11 @@ export const meta = {const TARGET_COMPONENTS = ['XDSDialog', 'XDSPopover'];+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);@@ -24,8 +29,8 @@ export default function transformer(file, api) {.find(j.JSXOpeningElement, {name: {name: componentName},})- .forEach((path) => {- path.node.attributes.forEach((attr) => {+ .forEach((/** @type {any} */ path) => {+ path.node.attributes.forEach((/** @type {any} */ attr) => {if (attr.type === 'JSXAttribute' && attr.name.name === 'isShown') {attr.name.name = 'isOpen';hasChanges = true;diff --git a/packages/cli/src/codemods/transforms/v0.0.2/rename-selector-items-to-options.mjs b/packages/cli/src/codemods/transforms/v0.0.2/rename-selector-items-to-options.mjsindex fec18a226d..c687ca6bb8 100644--- a/packages/cli/src/codemods/transforms/v0.0.2/rename-selector-items-to-options.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.2/rename-selector-items-to-options.mjs@@ -11,6 +11,11 @@ export const meta = {pr: '#479',};+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);@@ -21,8 +26,8 @@ export default function transformer(file, api) {.find(j.JSXOpeningElement, {name: {name: 'XDSSelector'},})- .forEach((path) => {- path.node.attributes.forEach((attr) => {+ .forEach((/** @type {any} */ path) => {+ path.node.attributes.forEach((/** @type {any} */ attr) => {if (attr.type === 'JSXAttribute' && attr.name.name === 'items') {attr.name.name = 'options';hasChanges = true;diff --git a/packages/cli/src/codemods/transforms/v0.0.2/rename-sidenav-header-to-heading.mjs b/packages/cli/src/codemods/transforms/v0.0.2/rename-sidenav-header-to-heading.mjsindex 54e3e2fe84..d2eb57a4a4 100644--- a/packages/cli/src/codemods/transforms/v0.0.2/rename-sidenav-header-to-heading.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.2/rename-sidenav-header-to-heading.mjs@@ -26,6 +26,7 @@ const TARGET_COMPONENTS = new Set(['XDSSideNavHeading',]);+/** @type {Record<string, string>} */const PROP_RENAMES = {title: 'heading',titleHref: 'headingHref',@@ -35,24 +36,30 @@ const PROP_RENAMES = {subtitleHref: 'subheadingHref',};+/** @type {Record<string, string>} */const IMPORT_RENAMES = {XDSSideNavHeader: 'XDSSideNavHeading',XDSSideNavHeaderProps: 'XDSSideNavHeadingProps',};+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);let hasChanges = false;// 1. Rename props on target components- root.find(j.JSXOpeningElement).forEach((path) => {+ root.find(j.JSXOpeningElement).forEach((/** @type {any} */ path) => {const name = path.node.name;if (name.type !== 'JSXIdentifier' || !TARGET_COMPONENTS.has(name.name)) {return;}- path.node.attributes.forEach((attr) => {+ path.node.attributes.forEach((/** @type {any} */ attr) => {if (attr.type === 'JSXAttribute' && attr.name.name in PROP_RENAMES) {attr.name.name = PROP_RENAMES[attr.name.name];hasChanges = true;@@ -61,13 +68,13 @@ export default function transformer(file, api) {});// 2. Rename <XDSSideNavHeader> to <XDSSideNavHeading> (opening and closing tags)- root.find(j.JSXIdentifier, {name: 'XDSSideNavHeader'}).forEach((path) => {+ root.find(j.JSXIdentifier, {name: 'XDSSideNavHeader'}).forEach((/** @type {any} */ path) => {path.node.name = 'XDSSideNavHeading';hasChanges = true;});// 3. Rename import specifiers- root.find(j.ImportSpecifier).forEach((path) => {+ root.find(j.ImportSpecifier).forEach((/** @type {any} */ path) => {const imported = path.node.imported;if (imported.type === 'Identifier' && imported.name in IMPORT_RENAMES) {const oldName = imported.name;diff --git a/packages/cli/src/codemods/transforms/v0.0.2/rename-topnav-title-to-heading.mjs b/packages/cli/src/codemods/transforms/v0.0.2/rename-topnav-title-to-heading.mjsindex 4aaa0769a0..6a64869a74 100644--- a/packages/cli/src/codemods/transforms/v0.0.2/rename-topnav-title-to-heading.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.2/rename-topnav-title-to-heading.mjs@@ -23,24 +23,30 @@ const TITLE_PROP_COMPONENTS = new Set(['XDSTopNavHeading',]);+/** @type {Record<string, string>} */const IMPORT_RENAMES = {XDSTopNavTitle: 'XDSTopNavHeading',XDSTopNavTitleProps: 'XDSTopNavHeadingProps',};+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);let hasChanges = false;// 1. Rename `title` prop to `heading` on target components- root.find(j.JSXOpeningElement).forEach((path) => {+ root.find(j.JSXOpeningElement).forEach((/** @type {any} */ path) => {const name = path.node.name;if (name.type !== 'JSXIdentifier' || !TITLE_PROP_COMPONENTS.has(name.name)) {return;}- path.node.attributes.forEach((attr) => {+ path.node.attributes.forEach((/** @type {any} */ attr) => {if (attr.type === 'JSXAttribute' && attr.name.name === 'title') {attr.name.name = 'heading';hasChanges = true;@@ -49,13 +55,13 @@ export default function transformer(file, api) {});// 2. Rename <XDSTopNavTitle> to <XDSTopNavHeading> (opening and closing tags)- root.find(j.JSXIdentifier, {name: 'XDSTopNavTitle'}).forEach((path) => {+ root.find(j.JSXIdentifier, {name: 'XDSTopNavTitle'}).forEach((/** @type {any} */ path) => {path.node.name = 'XDSTopNavHeading';hasChanges = true;});// 3. Rename import specifiers: XDSTopNavTitle → XDSTopNavHeading, XDSTopNavTitleProps → XDSTopNavHeadingProps- root.find(j.ImportSpecifier).forEach((path) => {+ root.find(j.ImportSpecifier).forEach((/** @type {any} */ path) => {const imported = path.node.imported;if (imported.type === 'Identifier' && imported.name in IMPORT_RENAMES) {const oldName = imported.name;diff --git a/packages/cli/src/codemods/transforms/v0.0.2/unify-uncontrolled-to-defaultX.mjs b/packages/cli/src/codemods/transforms/v0.0.2/unify-uncontrolled-to-defaultX.mjsindex 14db22e0ac..9912694a98 100644--- a/packages/cli/src/codemods/transforms/v0.0.2/unify-uncontrolled-to-defaultX.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.2/unify-uncontrolled-to-defaultX.mjs@@ -32,6 +32,11 @@ const RENAMES = [},];+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);@@ -42,8 +47,8 @@ export default function transformer(file, api) {.find(j.JSXOpeningElement, {name: {name: component},})- .forEach((path) => {- path.node.attributes.forEach((attr) => {+ .forEach((/** @type {any} */ path) => {+ path.node.attributes.forEach((/** @type {any} */ attr) => {if (attr.type === 'JSXAttribute' && attr.name.name === oldProp) {attr.name.name = newProp;hasChanges = true;diff --git a/packages/cli/src/codemods/transforms/v0.0.2/unify-visibility-to-onOpenChange.mjs b/packages/cli/src/codemods/transforms/v0.0.2/unify-visibility-to-onOpenChange.mjsindex eb1a584628..8f1207b42f 100644--- a/packages/cli/src/codemods/transforms/v0.0.2/unify-visibility-to-onOpenChange.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.2/unify-visibility-to-onOpenChange.mjs@@ -33,6 +33,11 @@ const SIMPLE_RENAMES = [*/const MERGE_COMPONENTS = ['XDSHoverCard', 'XDSTooltip'];+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);@@ -44,8 +49,8 @@ export default function transformer(file, api) {.find(j.JSXOpeningElement, {name: {name: component},})- .forEach((path) => {- path.node.attributes.forEach((attr) => {+ .forEach((/** @type {any} */ path) => {+ path.node.attributes.forEach((/** @type {any} */ attr) => {if (attr.type === 'JSXAttribute' && attr.name.name === oldProp) {attr.name.name = 'onOpenChange';hasChanges = true;@@ -60,13 +65,13 @@ export default function transformer(file, api) {.find(j.JSXOpeningElement, {name: {name: component},})- .forEach((path) => {+ .forEach((/** @type {any} */ path) => {const attrs = path.node.attributes;const onShowAttr = attrs.find(- (a) => a.type === 'JSXAttribute' && a.name.name === 'onShow',+ (/** @type {any} */ a) => a.type === 'JSXAttribute' && a.name.name === 'onShow',);const onHideAttr = attrs.find(- (a) => a.type === 'JSXAttribute' && a.name.name === 'onHide',+ (/** @type {any} */ a) => a.type === 'JSXAttribute' && a.name.name === 'onHide',);if (onShowAttr && onHideAttr) {diff --git a/packages/cli/src/codemods/transforms/v0.0.6/migrate-badge-children-to-label.mjs b/packages/cli/src/codemods/transforms/v0.0.6/migrate-badge-children-to-label.mjsindex 2607223c4a..be7968cc50 100644--- a/packages/cli/src/codemods/transforms/v0.0.6/migrate-badge-children-to-label.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.6/migrate-badge-children-to-label.mjs@@ -19,6 +19,11 @@ export const meta = {pr: '#706',};+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);@@ -28,7 +33,7 @@ export default function transformer(file, api) {.find(j.JSXElement, {openingElement: {name: {name: 'XDSBadge'}},})- .forEach((path) => {+ .forEach((/** @type {any} */ path) => {const {children} = path.node;// Skip if already self-closing or no children@@ -36,7 +41,7 @@ export default function transformer(file, api) {// Filter out whitespace-only JSXText nodesconst meaningful = children.filter(- (c) => !(c.type === 'JSXText' && !c.value.trim()),+ (/** @type {any} */ c) => !(c.type === 'JSXText' && !c.value.trim()),);// Only transform single-child casesdiff --git a/packages/cli/src/codemods/transforms/v0.0.6/migrate-collapse-to-collapsible.mjs b/packages/cli/src/codemods/transforms/v0.0.6/migrate-collapse-to-collapsible.mjsindex 4ddd00c950..4d2861699a 100644--- a/packages/cli/src/codemods/transforms/v0.0.6/migrate-collapse-to-collapsible.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.6/migrate-collapse-to-collapsible.mjs@@ -36,6 +36,11 @@ const APPSHELL_DEPRECATED_PROPS = ['defaultIsSideNavCollapsed',];+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);@@ -46,16 +51,17 @@ export default function transformer(file, api) {.find(j.JSXOpeningElement, {name: {name: 'XDSSideNav'},})- .forEach((path) => {+ .forEach((/** @type {any} */ path) => {const attrs = path.node.attributes;// Find isCollapsibleconst isCollapsibleIdx = attrs.findIndex(- (a) => a.type === 'JSXAttribute' && a.name.name === 'isCollapsible',+ (/** @type {any} */ a) => a.type === 'JSXAttribute' && a.name.name === 'isCollapsible',);if (isCollapsibleIdx === -1) return;// Collect all collapse-related props+ /** @type {Record<string, any>} */const collapseProps = {};const indicesToRemove = [];@@ -129,7 +135,7 @@ export default function transformer(file, api) {.find(j.JSXOpeningElement, {name: {name: 'XDSAppShell'},})- .forEach((path) => {+ .forEach((/** @type {any} */ path) => {const attrs = path.node.attributes;for (let i = attrs.length - 1; i >= 0; i--) {const attr = attrs[i];diff --git a/packages/cli/src/codemods/transforms/v0.0.6/migrate-radius-tokens.mjs b/packages/cli/src/codemods/transforms/v0.0.6/migrate-radius-tokens.mjsindex 9c209e7506..235c827724 100644--- a/packages/cli/src/codemods/transforms/v0.0.6/migrate-radius-tokens.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.6/migrate-radius-tokens.mjs@@ -22,6 +22,7 @@ export const meta = {'Renames --radius-inner/content/element/container/page to --radius-0/1/2/3/4.',};+/** @type {Record<string, string>} */const TOKEN_MAP = {'--radius-inner': '--radius-0','--radius-content': '--radius-1',@@ -38,17 +39,22 @@ const OLD_TOKENS_PATTERN = new RegExp('g',);-function replaceTokens(str) {- return str.replace(OLD_TOKENS_PATTERN, (match) => TOKEN_MAP[match] || match);+function replaceTokens(/** @type {any} */ str) {+ return str.replace(OLD_TOKENS_PATTERN, (/** @type {any} */ match) => TOKEN_MAP[match] || match);}+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);let hasChanges = false;// Replace in string literals (StringLiteral or Literal with string value)- const replaceInStringNode = (path) => {+ const replaceInStringNode = (/** @type {any} */ path) => {if (typeof path.node.value !== 'string') return;const original = path.node.value;const replaced = replaceTokens(original);@@ -59,14 +65,14 @@ export default function transformer(file, api) {};root.find(j.StringLiteral).forEach(replaceInStringNode);- root.find(j.Literal).forEach((path) => {+ root.find(j.Literal).forEach((/** @type {any} */ path) => {if (typeof path.node.value === 'string') {replaceInStringNode(path);}});// Replace in template literal quasis- root.find(j.TemplateLiteral).forEach((path) => {+ root.find(j.TemplateLiteral).forEach((/** @type {any} */ path) => {for (const quasi of path.node.quasis) {const original = quasi.value.raw;const replaced = replaceTokens(original);diff --git a/packages/cli/src/codemods/transforms/v0.0.6/migrate-shadow-tokens.mjs b/packages/cli/src/codemods/transforms/v0.0.6/migrate-shadow-tokens.mjsindex 4fff6c3784..396fc5ae9f 100644--- a/packages/cli/src/codemods/transforms/v0.0.6/migrate-shadow-tokens.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.6/migrate-shadow-tokens.mjs@@ -34,6 +34,7 @@ export const meta = {'Renames --elevation-* to --shadow-base/menu/hover/dialog and --inset-shadow-border-*. Also migrates --shadow-1/2/3/4 from the brief numeric naming period.',};+/** @type {Record<string, string>} */const TOKEN_MAP = {'--elevation-input-hover-success': '--inset-shadow-border-positive','--elevation-input-hover-warning': '--inset-shadow-border-warning',@@ -49,6 +50,7 @@ const TOKEN_MAP = {'--shadow-4': '--shadow-dialog',};+/** @type {Record<string, string>} */const IDENTIFIER_MAP = {elevationDefaults: 'shadowDefaults',elevationVars: 'shadowVars',@@ -64,16 +66,21 @@ const OLD_TOKENS_PATTERN = new RegExp('g',);-function replaceTokens(str) {- return str.replace(OLD_TOKENS_PATTERN, (match) => TOKEN_MAP[match] || match);+function replaceTokens(/** @type {any} */ str) {+ return str.replace(OLD_TOKENS_PATTERN, (/** @type {any} */ match) => TOKEN_MAP[match] || match);}+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);let hasChanges = false;- const replaceInStringNode = (path) => {+ const replaceInStringNode = (/** @type {any} */ path) => {if (typeof path.node.value !== 'string') return;const original = path.node.value;const replaced = replaceTokens(original);@@ -84,11 +91,11 @@ export default function transformer(file, api) {};root.find(j.StringLiteral).forEach(replaceInStringNode);- root.find(j.Literal).forEach((path) => {+ root.find(j.Literal).forEach((/** @type {any} */ path) => {if (typeof path.node.value === 'string') replaceInStringNode(path);});- root.find(j.TemplateLiteral).forEach((path) => {+ root.find(j.TemplateLiteral).forEach((/** @type {any} */ path) => {for (const quasi of path.node.quasis) {const originalRaw = quasi.value.raw;const replacedRaw = replaceTokens(originalRaw);@@ -100,7 +107,7 @@ export default function transformer(file, api) {}});- root.find(j.Identifier).forEach((path) => {+ root.find(j.Identifier).forEach((/** @type {any} */ path) => {if (Object.hasOwn(IDENTIFIER_MAP, path.node.name)) {path.node.name = IDENTIFIER_MAP[path.node.name];hasChanges = true;diff --git a/packages/cli/src/codemods/transforms/v0.0.6/migrate-skeleton-radius.mjs b/packages/cli/src/codemods/transforms/v0.0.6/migrate-skeleton-radius.mjsindex 066b680ce6..10f5aff910 100644--- a/packages/cli/src/codemods/transforms/v0.0.6/migrate-skeleton-radius.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.6/migrate-skeleton-radius.mjs@@ -16,6 +16,7 @@ export const meta = {'Replaces semantic radius prop values (inner, content, element, container) with numeric equivalents (0, 1, 2, 3).',};+/** @type {Record<string, number>} */const RADIUS_MAP = {inner: 0,content: 1,@@ -23,6 +24,11 @@ const RADIUS_MAP = {container: 3,};+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);@@ -32,7 +38,7 @@ export default function transformer(file, api) {.find(j.JSXOpeningElement, {name: {name: 'XDSSkeleton'},})- .forEach((path) => {+ .forEach((/** @type {any} */ path) => {const attrs = path.node.attributes;for (const attr of attrs) {if (attr.type !== 'JSXAttribute') continue;diff --git a/packages/cli/src/codemods/transforms/v0.0.6/migrate-token-names.mjs b/packages/cli/src/codemods/transforms/v0.0.6/migrate-token-names.mjsindex 79bd41e222..731f313bef 100644--- a/packages/cli/src/codemods/transforms/v0.0.6/migrate-token-names.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.6/migrate-token-names.mjs@@ -66,6 +66,7 @@ export const meta = {// Ordered longest-first to prevent partial matches// (e.g. --color-educational-deemphasized must match before --color-educational)+/** @type {Record<string, string>} */const TOKEN_MAP = {'--color-educational-deemphasized': '--color-info-muted','--color-divider-high-contrast': '--color-border-strong',@@ -114,17 +115,22 @@ const OLD_TOKENS_PATTERN = new RegExp('g',);-function replaceTokens(str) {- return str.replace(OLD_TOKENS_PATTERN, (match) => TOKEN_MAP[match] || match);+function replaceTokens(/** @type {any} */ str) {+ return str.replace(OLD_TOKENS_PATTERN, (/** @type {any} */ match) => TOKEN_MAP[match] || match);}+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);let hasChanges = false;// Replace in string literals (StringLiteral or Literal with string value)- const replaceInStringNode = (path) => {+ const replaceInStringNode = (/** @type {any} */ path) => {if (typeof path.node.value !== 'string') return;const original = path.node.value;const replaced = replaceTokens(original);@@ -135,14 +141,14 @@ export default function transformer(file, api) {};root.find(j.StringLiteral).forEach(replaceInStringNode);- root.find(j.Literal).forEach((path) => {+ root.find(j.Literal).forEach((/** @type {any} */ path) => {if (typeof path.node.value === 'string') {replaceInStringNode(path);}});// Replace in template literal quasis- root.find(j.TemplateLiteral).forEach((path) => {+ root.find(j.TemplateLiteral).forEach((/** @type {any} */ path) => {for (const quasi of path.node.quasis) {const original = quasi.value.raw;const replaced = replaceTokens(original);diff --git a/packages/cli/src/codemods/transforms/v0.0.7/rename-banner-variant-to-container.mjs b/packages/cli/src/codemods/transforms/v0.0.7/rename-banner-variant-to-container.mjsindex 5f39aefb3e..456f868298 100644--- a/packages/cli/src/codemods/transforms/v0.0.7/rename-banner-variant-to-container.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.7/rename-banner-variant-to-container.mjs@@ -20,6 +20,11 @@ export const meta = {pr: '#814',};+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);@@ -30,8 +35,8 @@ export default function transformer(file, api) {.find(j.JSXOpeningElement, {name: {name: 'XDSBanner'},})- .forEach((path) => {- path.node.attributes.forEach((attr) => {+ .forEach((/** @type {any} */ path) => {+ path.node.attributes.forEach((/** @type {any} */ attr) => {if (attr.type === 'JSXAttribute' && attr.name.name === 'variant') {attr.name.name = 'container';hasChanges = true;@@ -40,7 +45,7 @@ export default function transformer(file, api) {});// 2. Rename type references: XDSBannerVariant → XDSBannerContainer- root.find(j.Identifier, {name: 'XDSBannerVariant'}).forEach((path) => {+ root.find(j.Identifier, {name: 'XDSBannerVariant'}).forEach((/** @type {any} */ path) => {path.node.name = 'XDSBannerContainer';hasChanges = true;});diff --git a/packages/cli/src/codemods/transforms/v0.0.8/migrate-token-renames.mjs b/packages/cli/src/codemods/transforms/v0.0.8/migrate-token-renames.mjsindex 792bb1c474..f7df6e11f8 100644--- a/packages/cli/src/codemods/transforms/v0.0.8/migrate-token-renames.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.8/migrate-token-renames.mjs@@ -50,6 +50,7 @@ export const meta = {// Token string renames (CSS custom property names)// =============================================================================+/** @type {Record<string, string>} */const TOKEN_MAP = {// Color — Core Semantic'--color-secondary': '--color-neutral',@@ -195,6 +196,7 @@ const TOKEN_MAP = {// JS identifier renames (import names, variable references)// =============================================================================+/** @type {Record<string, string>} */const IDENTIFIER_MAP = {lineHeightVars: 'typeScaleVars',lineHeightDefaults: 'typeScaleDefaults',@@ -213,21 +215,26 @@ const OLD_TOKENS_PATTERN = new RegExp('g',);-function replaceTokens(str) {- return str.replace(OLD_TOKENS_PATTERN, (match) => TOKEN_MAP[match] || match);+function replaceTokens(/** @type {any} */ str) {+ return str.replace(OLD_TOKENS_PATTERN, (/** @type {any} */ match) => TOKEN_MAP[match] || match);}// =============================================================================// Transformer// =============================================================================+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);let hasChanges = false;// --- Pass 1: Rename token strings in string literals ---- const replaceInStringNode = (path) => {+ const replaceInStringNode = (/** @type {any} */ path) => {if (typeof path.node.value !== 'string') return;const original = path.node.value;const replaced = replaceTokens(original);@@ -238,14 +245,14 @@ export default function transformer(file, api) {};root.find(j.StringLiteral).forEach(replaceInStringNode);- root.find(j.Literal).forEach((path) => {+ root.find(j.Literal).forEach((/** @type {any} */ path) => {if (typeof path.node.value === 'string') {replaceInStringNode(path);}});// --- Pass 2: Rename token strings in template literals ---- root.find(j.TemplateLiteral).forEach((path) => {+ root.find(j.TemplateLiteral).forEach((/** @type {any} */ path) => {for (const quasi of path.node.quasis) {const original = quasi.value.raw;const replaced = replaceTokens(original);@@ -263,7 +270,7 @@ export default function transformer(file, api) {// Special handling for imports: if the target name already exists as an import// specifier in the same declaration, remove the old specifier instead of renaming// it (avoids duplicate identifier declarations).- root.find(j.ImportSpecifier).forEach((importPath) => {+ root.find(j.ImportSpecifier).forEach((/** @type {any} */ importPath) => {const oldName = importPath.node.imported.name;if (!Object.hasOwn(IDENTIFIER_MAP, oldName)) return;@@ -271,7 +278,7 @@ export default function transformer(file, api) {const declaration = importPath.parent.node;const siblings = declaration.specifiers || [];const targetExists = siblings.some(- (s) =>+ (/** @type {any} */ s) =>s !== importPath.node &&s.type === 'ImportSpecifier' &&s.imported.name === newName,@@ -295,7 +302,7 @@ export default function transformer(file, api) {});// Rename remaining non-import identifier references- root.find(j.Identifier).forEach((path) => {+ root.find(j.Identifier).forEach((/** @type {any} */ path) => {if (!Object.hasOwn(IDENTIFIER_MAP, path.node.name)) return;// Skip import specifiers (already handled above)if (path.parent.node.type === 'ImportSpecifier') return;diff --git a/packages/cli/src/codemods/transforms/v0.0.8/rename-endslot-to-endcontent.mjs b/packages/cli/src/codemods/transforms/v0.0.8/rename-endslot-to-endcontent.mjsindex 1d235a3065..5bc9111e9e 100644--- a/packages/cli/src/codemods/transforms/v0.0.8/rename-endslot-to-endcontent.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.8/rename-endslot-to-endcontent.mjs@@ -23,13 +23,18 @@ export const meta = {pr: '#895',};+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);let hasChanges = false;// 1. Rename JSX prop: <XDSButton endSlot={...} /> → <XDSButton endContent={...} />- root.find(j.JSXAttribute, {name: {name: 'endSlot'}}).forEach((path) => {+ root.find(j.JSXAttribute, {name: {name: 'endSlot'}}).forEach((/** @type {any} */ path) => {path.node.name.name = 'endContent';hasChanges = true;});@@ -37,7 +42,7 @@ export default function transformer(file, api) {// 2. Rename in all Identifier nodes named 'endSlot' that are object keys// This covers both Property and ObjectProperty (parser-dependent),// object literals, destructuring patterns, etc.- root.find(j.Identifier, {name: 'endSlot'}).forEach((path) => {+ root.find(j.Identifier, {name: 'endSlot'}).forEach((/** @type {any} */ path) => {const parent = path.parent.node;// Object property key: { endSlot: value } or { endSlot } (shorthand)diff --git a/packages/cli/src/codemods/transforms/v0.1.0/drop-xds-prefix-imports.mjs b/packages/cli/src/codemods/transforms/v0.1.0/drop-xds-prefix-imports.mjsindex d08513e9d7..02787b1fcb 100644--- a/packages/cli/src/codemods/transforms/v0.1.0/drop-xds-prefix-imports.mjs+++ b/packages/cli/src/codemods/transforms/v0.1.0/drop-xds-prefix-imports.mjs@@ -68,7 +68,7 @@ const XDS_CORE_SOURCE = /^@xds\/core(\/.*)?$/;* Compute the bare (unprefixed) name for an XDS-prefixed identifier.* Returns null if the name is not XDS-prefixed in a renameable way.*/-function bareName(name) {+function bareName(/** @type {any} */ name) {if (name.startsWith('useXDS') && name.length > 'useXDS'.length) {return 'use' + name.slice('useXDS'.length);}@@ -91,7 +91,7 @@ function bareName(name) {const MOCK_METHOD_NAMES = new Set(['mock', 'doMock']);const MOCK_OBJECT_NAMES = new Set(['vi', 'jest']);-function isMockCallee(callee) {+function isMockCallee(/** @type {any} */ callee) {if (callee.type === 'MemberExpression' &&!callee.computed &&@@ -105,7 +105,7 @@ function isMockCallee(callee) {return callee.type === 'Identifier' && callee.name === 'mock';}-function isXdsCoreMockCall(node) {+function isXdsCoreMockCall(/** @type {any} */ node) {if (node.type !== 'CallExpression' || !isMockCallee(node.callee))return false;const [arg] = node.arguments;@@ -119,7 +119,7 @@ function isXdsCoreMockCall(node) {// Rename XDS-prefixed object-property KEYS (not values, not nested objects)// within the given AST subtree. Used only on a recognized @xds/core mock// factory, so the scope guard lives at the call site.-function renameMockFactoryKeys(node, seen, onChange) {+function renameMockFactoryKeys(/** @type {any} */ node, /** @type {any} */ seen, /** @type {any} */ onChange) {if (!node || typeof node !== 'object') return;if (Array.isArray(node)) {for (const child of node) renameMockFactoryKeys(child, seen, onChange);@@ -158,6 +158,11 @@ function renameMockFactoryKeys(node, seen, onChange) {}}+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);@@ -176,12 +181,12 @@ export default function transformer(file, api) {// declaration. We gather: import locals, and top-level function/class/var// declaration names (the realistic collision sources for component wrappers).const existingBindings = new Set();- root.find(j.ImportDeclaration).forEach(path => {+ root.find(j.ImportDeclaration).forEach((/** @type {any} */ path) => {for (const spec of path.node.specifiers || []) {if (spec.local && spec.local.name) existingBindings.add(spec.local.name);}});- const collectDeclName = node => {+ const collectDeclName = (/** @type {any} */ node) => {if (!node) return;if ((node.type === 'FunctionDeclaration' ||@@ -195,7 +200,7 @@ export default function transformer(file, api) {}}};- root.find(j.Program).forEach(path => {+ root.find(j.Program).forEach((/** @type {any} */ path) => {for (const stmt of path.node.body) {collectDeclName(stmt);// Unwrap `export function X` / `export const X`.@@ -209,11 +214,11 @@ export default function transformer(file, api) {});// 1. Rewrite import specifiers from @xds/core- root.find(j.ImportDeclaration).forEach(path => {+ root.find(j.ImportDeclaration).forEach((/** @type {any} */ path) => {const source = path.node.source.value;if (typeof source !== 'string' || !XDS_CORE_SOURCE.test(source)) return;- path.node.specifiers = (path.node.specifiers || []).map(spec => {+ path.node.specifiers = (path.node.specifiers || []).map((/** @type {any} */ spec) => {if (spec.type !== 'ImportSpecifier') return spec; // default/namespaceconst importedName = spec.imported.name;const bare = bareName(importedName);@@ -253,7 +258,7 @@ export default function transformer(file, api) {});// 2. Rewrite re-exports from @xds/core- root.find(j.ExportNamedDeclaration).forEach(path => {+ root.find(j.ExportNamedDeclaration).forEach((/** @type {any} */ path) => {if (!path.node.source) return;const source = path.node.source.value;if (typeof source !== 'string' || !XDS_CORE_SOURCE.test(source)) return;@@ -279,7 +284,7 @@ export default function transformer(file, api) {// not a reference to an imported binding, so it must match the renamed export// name of the mocked module regardless of what the file imports.const seenMockNodes = new Set();- root.find(j.CallExpression).forEach(path => {+ root.find(j.CallExpression).forEach((/** @type {any} */ path) => {if (!isXdsCoreMockCall(path.node)) return;// Only walk the factory argument(s), never the module-path string.for (const arg of path.node.arguments.slice(1)) {@@ -295,7 +300,7 @@ export default function transformer(file, api) {// 4. Rename references to renamed local bindings// Identifiers (type refs, value refs, etc.)- root.find(j.Identifier).forEach(path => {+ root.find(j.Identifier).forEach((/** @type {any} */ path) => {const newName = localRenames.get(path.node.name);if (!newName) return;// Skip object property keys like `{ XDSButton: ... }` (not a reference to@@ -322,7 +327,7 @@ export default function transformer(file, api) {});// JSX element names: <XDSButton> -> <Button>- root.find(j.JSXIdentifier).forEach(path => {+ root.find(j.JSXIdentifier).forEach((/** @type {any} */ path) => {const newName = localRenames.get(path.node.name);if (newName) {path.node.name = newName;@@ -344,7 +349,7 @@ export default function transformer(file, api) {// renamed binding. Renaming already-bare names is a no-op, so re-visiting a// node the earlier passes handled is harmless.const seenTypeNodes = new Set();- const renameTypeReferences = node => {+ const renameTypeReferences = (/** @type {any} */ node) => {if (!node || typeof node !== 'object') return;if (Array.isArray(node)) {for (const child of node) renameTypeReferences(child);diff --git a/packages/cli/src/codemods/transforms/v0.1.0/migrate-xds-css-surfaces.mjs b/packages/cli/src/codemods/transforms/v0.1.0/migrate-xds-css-surfaces.mjsindex 7ac8a0d3b6..37a2dd83f4 100644--- a/packages/cli/src/codemods/transforms/v0.1.0/migrate-xds-css-surfaces.mjs+++ b/packages/cli/src/codemods/transforms/v0.1.0/migrate-xds-css-surfaces.mjs@@ -9,19 +9,18 @@* consumer CSS that targeted those surfaces is now broken.** This transform performs precise, targeted string replacements on CSS/SCSS- * files for the documented surfaces only:+ * files for the documented surfaces only (selectors, layer names, and package+ * stylesheet imports):*- * .xds-* (class-name prefix in selectors — matched only- * after a `.` so it is a class selector)- * [data-xds-theme (theme attribute selector)- * [data-xds-theme-prose (prose-theme attribute selector)- * [data-xds-media (media attribute selector)- * @layer xds-theme (cascade layer name — incl. comma-separated- * @layer xds-base `@layer a, b;` statement lists and nested blocks)- * @import '@xds/...' (package stylesheet imports — scope rewrite, plus- * the @xds/core/xds.css -> @astryxdesign/core/- * astryx.css file rename and the theme-default /- * theme-daily -> theme-neutral collapse)+ * - `.xds-*` class-name prefix in selectors (matched only after a `.` so it is+ * a class selector).+ * - `[data-xds-theme`, `[data-xds-theme-prose`, `[data-xds-media` attribute+ * selectors.+ * - `\@layer xds-theme` / `\@layer xds-base` cascade layer names, including+ * comma-separated `\@layer a, b;` statement lists and nested blocks.+ * - `\@import '\@xds/...'` package stylesheet imports: scope rewrite, plus the+ * `\@xds/core/xds.css` -> `\@astryxdesign/core/astryx.css` file rename and the+ * `theme-default` / `theme-daily` -> `theme-neutral` collapse.** It deliberately does NOT blindly replace every `xds` substring: a bare* `xds` in a comment, a custom-property value, or an unrelated identifier is@@ -51,8 +50,8 @@ const XDS_LAYER_NAMES = new Map([['xds-base', 'astryx-base'],]);-function rewriteLayerPrelude(prelude) {- return prelude.replace(/\bxds-(?:theme|base)\b/g, name =>+function rewriteLayerPrelude(/** @type {any} */ prelude) {+ return prelude.replace(/\bxds-(?:theme|base)\b/g, (/** @type {any} */ name) =>XDS_LAYER_NAMES.get(name) ?? name,);}@@ -64,7 +63,7 @@ function rewriteLayerPrelude(prelude) {// @xds/theme-default/* -> @astryxdesign/theme-neutral/* (collapse)// @xds/theme-daily/* -> @astryxdesign/theme-neutral/* (collapse)// Returns the original value unchanged if it is not an @xds/* specifier.-function rewriteImportSpecifier(spec) {+function rewriteImportSpecifier(/** @type {any} */ spec) {if (!spec.startsWith('@xds/')) return spec;// Theme package collapse (default/daily -> neutral).let next = spec@@ -85,6 +84,7 @@ function rewriteImportSpecifier(spec) {// Ordered, non-overlapping replacements. Each pattern is intentionally narrow// so we never touch a bare `xds` substring outside these surfaces.+/** @type {Array<{re: RegExp, to: any}>} */const REPLACEMENTS = [// Class-name prefix: only when preceded by a `.` (a class selector).{re: /\.xds-/g, to: '.astryx-'},@@ -92,18 +92,22 @@ const REPLACEMENTS = [{re: /\[data-xds-/g, to: '[data-astryx-'},// Cascade-layer preludes: `@layer <names>` up to the block `{` or `;`.// Rewrite only the recognized xds-* layer tokens inside the prelude.- {re: /@layer\b[^{;]*/g, to: match => rewriteLayerPrelude(match)},+ {re: /@layer\b[^{;]*/g, to: (/** @type {any} */ match) => rewriteLayerPrelude(match)},// Package stylesheet imports: `@import '@xds/...'` or `@import url('@xds/...')`.// Rewrite only the quoted @xds/* specifier, preserving the quote style.{re: /@import\s+(?:url\(\s*)?(['"])(@xds\/[^'"]+)\1/g,- to: (match, quote, spec) => {+ to: (/** @type {any} */ match, /** @type {any} */ quote, /** @type {any} */ spec) => {const next = rewriteImportSpecifier(spec);return next === spec ? match : match.replace(spec, next);},},];+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @returns {string | null | undefined}+ */export default function transformer(file /*, api */) {const source = file.source;if (typeof source !== 'string') return undefined;diff --git a/packages/cli/src/codemods/transforms/v0.1.0/migrate-xds-declare-module.mjs b/packages/cli/src/codemods/transforms/v0.1.0/migrate-xds-declare-module.mjsindex 5a4ebf9ed7..21bd103bf5 100644--- a/packages/cli/src/codemods/transforms/v0.1.0/migrate-xds-declare-module.mjs+++ b/packages/cli/src/codemods/transforms/v0.1.0/migrate-xds-declare-module.mjs@@ -48,7 +48,7 @@ const PACKAGE_RENAMES = new Map([['@xds/theme-y2k', '@astryxdesign/theme-y2k'],]);-function renamePackageSpecifier(value) {+function renamePackageSpecifier(/** @type {any} */ value) {if (typeof value !== 'string') return value;for (const [from, to] of PACKAGE_RENAMES) {if (value === from) return to;@@ -57,12 +57,17 @@ function renamePackageSpecifier(value) {return value;}+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);let hasChanges = false;- root.find(j.TSModuleDeclaration).forEach(path => {+ root.find(j.TSModuleDeclaration).forEach((/** @type {any} */ path) => {const id = path.node.id;// Module augmentations name the module with a string literal id; a// `namespace Foo {}` uses an Identifier id, which we ignore.diff --git a/packages/cli/src/codemods/transforms/v0.1.0/migrate-xds-module-specifiers.mjs b/packages/cli/src/codemods/transforms/v0.1.0/migrate-xds-module-specifiers.mjsindex fe7332f02e..2832da5feb 100644--- a/packages/cli/src/codemods/transforms/v0.1.0/migrate-xds-module-specifiers.mjs+++ b/packages/cli/src/codemods/transforms/v0.1.0/migrate-xds-module-specifiers.mjs@@ -35,7 +35,7 @@ const PACKAGE_RENAMES = new Map([['@xds/theme-y2k', '@astryxdesign/theme-y2k'],]);-function renamePackageSpecifier(value) {+function renamePackageSpecifier(/** @type {any} */ value) {if (typeof value !== 'string') return value;for (const [from, to] of PACKAGE_RENAMES) {if (value === from) return to;@@ -44,7 +44,7 @@ function renamePackageSpecifier(value) {return value;}-function rewriteLiteral(node) {+function rewriteLiteral(/** @type {any} */ node) {if (!node || typeof node.value !== 'string') return false;const next = renamePackageSpecifier(node.value);if (next === node.value) return false;@@ -66,7 +66,7 @@ const COLLAPSED_THEME_SOURCES = new Set(['@xds/theme-daily',]);-function isCollapsedThemeSource(value) {+function isCollapsedThemeSource(/** @type {any} */ value) {if (typeof value !== 'string') return false;for (const src of COLLAPSED_THEME_SOURCES) {if (value === src || value.startsWith(src + '/')) return true;@@ -84,7 +84,7 @@ function isCollapsedThemeSource(value) {const MOCK_METHOD_NAMES = new Set(['mock', 'doMock']);const MOCK_OBJECT_NAMES = new Set(['vi', 'jest']);-function isMockCall(callee) {+function isMockCall(/** @type {any} */ callee) {if (callee.type === 'MemberExpression' &&!callee.computed &&@@ -98,9 +98,9 @@ function isMockCall(callee) {return callee.type === 'Identifier' && callee.name === 'mock';}-function remapThemeExportNames(importPath, j) {+function remapThemeExportNames(/** @type {any} */ importPath, /** @type {any} */ j) {let changed = false;- importPath.node.specifiers = (importPath.node.specifiers || []).map(spec => {+ importPath.node.specifiers = (importPath.node.specifiers || []).map((/** @type {any} */ spec) => {if (spec.type !== 'ImportSpecifier') return spec;const importedName = spec.imported.name;const renamed = THEME_EXPORT_RENAMES.get(importedName);@@ -116,12 +116,17 @@ function remapThemeExportNames(importPath, j) {return changed;}+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);let hasChanges = false;- root.find(j.ImportDeclaration).forEach(path => {+ root.find(j.ImportDeclaration).forEach((/** @type {any} */ path) => {// Remap collapsed-theme export names BEFORE rewriting the source specifier// (the check keys off the original @xds/theme-default|daily path).if (isCollapsedThemeSource(path.node.source.value)) {@@ -130,15 +135,15 @@ export default function transformer(file, api) {hasChanges = rewriteLiteral(path.node.source) || hasChanges;});- root.find(j.ExportNamedDeclaration).forEach(path => {+ root.find(j.ExportNamedDeclaration).forEach((/** @type {any} */ path) => {hasChanges = rewriteLiteral(path.node.source) || hasChanges;});- root.find(j.ExportAllDeclaration).forEach(path => {+ root.find(j.ExportAllDeclaration).forEach((/** @type {any} */ path) => {hasChanges = rewriteLiteral(path.node.source) || hasChanges;});- root.find(j.CallExpression).forEach(path => {+ root.find(j.CallExpression).forEach((/** @type {any} */ path) => {const isDynamicImport = path.node.callee.type === 'Import';const isRequire =path.node.callee.type === 'Identifier' &&@@ -160,7 +165,7 @@ export default function transformer(file, api) {// position. Re-visiting a node the loop above handled is harmless: the// literal is already rewritten, so the second pass is a no-op.const seenTypeImportNodes = new Set();- const rewriteTSImportTypes = node => {+ const rewriteTSImportTypes = (/** @type {any} */ node) => {if (!node || typeof node !== 'object') return;if (Array.isArray(node)) {for (const child of node) rewriteTSImportTypes(child);diff --git a/packages/cli/src/codemods/transforms/v0.1.2/rename-text-color-active-to-accent.mjs b/packages/cli/src/codemods/transforms/v0.1.2/rename-text-color-active-to-accent.mjsindex b75cc014c2..005cfebd75 100644--- a/packages/cli/src/codemods/transforms/v0.1.2/rename-text-color-active-to-accent.mjs+++ b/packages/cli/src/codemods/transforms/v0.1.2/rename-text-color-active-to-accent.mjs@@ -40,13 +40,18 @@ const NEW_VALUE = 'accent';/** Components whose `color` prop accepts a TextColor value. */const TARGET_COMPONENTS = new Set(['Text', 'Heading', 'Link', 'Timestamp']);+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);let hasChanges = false;/** Rewrite a string-literal node when it equals the old value. */- function renameStringLiteral(node) {+ function renameStringLiteral(/** @type {any} */ node) {if (!node) return false;if ((node.type === 'StringLiteral' || node.type === 'Literal') &&@@ -60,7 +65,8 @@ export default function transformer(file, api) {}/** Recursively rewrite the old value inside ternary/logical expressions. */- function renameInExpression(node) {+ /** @returns {boolean} */+ function renameInExpression(/** @type {any} */ node) {if (!node) return false;let changed = false;if (node.type === 'StringLiteral' || node.type === 'Literal') {@@ -79,12 +85,12 @@ export default function transformer(file, api) {}// --- 1. JSX attribute: color="active" / color={'active'} on target components ---- root.find(j.JSXOpeningElement).forEach(path => {+ root.find(j.JSXOpeningElement).forEach((/** @type {any} */ path) => {const name = path.node.name;const componentName = name.type === 'JSXIdentifier' ? name.name : null;if (!componentName || !TARGET_COMPONENTS.has(componentName)) return;- path.node.attributes.forEach(attr => {+ path.node.attributes.forEach((/** @type {any} */ attr) => {if (attr.type !== 'JSXAttribute') return;if (!attr.name || attr.name.name !== 'color') return;@@ -104,27 +110,27 @@ export default function transformer(file, api) {const importsTarget =root.find(j.ImportSpecifier)- .filter(p => TARGET_COMPONENTS.has(p.node.imported?.name))+ .filter((/** @type {any} */ p) => TARGET_COMPONENTS.has(p.node.imported?.name)).size() > 0;if (importsTarget) {const PropertyType = j.ObjectProperty ?? j.Property;// --- 2. Object property: { color: 'active' } / { color: 'active' as const } ---- root.find(PropertyType, {key: {name: 'color'}}).forEach(path => {+ root.find(PropertyType, {key: {name: 'color'}}).forEach((/** @type {any} */ path) => {if (renameInExpression(path.node.value)) hasChanges = true;});// --- 3. Storybook argTypes: color: { options: [..., 'active', ...] } ---- root.find(PropertyType, {key: {name: 'color'}}).forEach(path => {+ root.find(PropertyType, {key: {name: 'color'}}).forEach((/** @type {any} */ path) => {const value = path.node.value;if (!value || value.type !== 'ObjectExpression') return;const optionsProp = value.properties.find(- p => p.key && (p.key.name === 'options' || p.key.value === 'options'),+ (/** @type {any} */ p) => p.key && (p.key.name === 'options' || p.key.value === 'options'),);if (optionsProp && optionsProp.value.type === 'ArrayExpression') {- optionsProp.value.elements.forEach(el => {+ optionsProp.value.elements.forEach((/** @type {any} */ el) => {if (renameStringLiteral(el)) hasChanges = true;});}diff --git a/packages/cli/src/codemods/transforms/v0.1.3/migrate-layout-components-to-experimental.mjs b/packages/cli/src/codemods/transforms/v0.1.3/migrate-layout-components-to-experimental.mjsindex fc14026a8c..b7ef0d8510 100644--- a/packages/cli/src/codemods/transforms/v0.1.3/migrate-layout-components-to-experimental.mjs+++ b/packages/cli/src/codemods/transforms/v0.1.3/migrate-layout-components-to-experimental.mjs@@ -58,6 +58,11 @@ const MANUAL =* @param {{jscodeshift: Function}} api* @returns {string|null}*/+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);@@ -105,7 +110,7 @@ export default function transformer(file, api) {// `components` was the only documented `layout` key. Anything else is// unexpected and we cannot safely guess intent.const otherLayoutKeys = layoutProp.value.properties.filter(- p => p !== componentsProp,+ (/** @type {any} */ p) => p !== componentsProp,);if (otherLayoutKeys.length > 0) {throw new Error(@@ -148,7 +153,7 @@ export default function transformer(file, api) {// Remove the migrated data from `layout`. Since `components` was the only// key (asserted above), remove the entire `layout` property.configObject.properties = configObject.properties.filter(- p => p !== layoutProp,+ (/** @type {any} */ p) => p !== layoutProp,);return root.toSource();@@ -157,9 +162,9 @@ export default function transformer(file, api) {/*** Resolve the wrapped config object literal from a default-export declaration.* Handles `{ ... }` and `createConfig({ ... })`.- * @returns {object|null} the ObjectExpression node, or null if not analyzable+ * @returns {any} the ObjectExpression node, or null if not analyzable*/-function resolveConfigObject(j, declaration) {+function resolveConfigObject(/** @type {any} */ j, /** @type {any} */ declaration) {if (!declaration) return null;if (j.ObjectExpression.check(declaration)) {return declaration;@@ -177,10 +182,10 @@ function resolveConfigObject(j, declaration) {/*** Find a (non-computed, non-spread) property on an object literal by key name.* Supports Identifier and string-literal keys.- * @returns {object|undefined} the property node+ * @returns {any} the property node*/-function findObjectProperty(j, objectExpression, name) {- return objectExpression.properties.find(prop => {+function findObjectProperty(/** @type {any} */ j, /** @type {any} */ objectExpression, /** @type {any} */ name) {+ return objectExpression.properties.find((/** @type {any} */ prop) => {if (!j.ObjectProperty.check(prop) &&!j.Property.check(prop)@@ -200,8 +205,8 @@ function findObjectProperty(j, objectExpression, name) {* Build the migrated `components` ObjectExpression from the old one.* @returns {object} ObjectExpression*/-function buildMigratedComponents(j, oldComponents) {- const newProps = oldComponents.properties.map(prop => {+function buildMigratedComponents(/** @type {any} */ j, /** @type {any} */ oldComponents) {+ const newProps = oldComponents.properties.map((/** @type {any} */ prop) => {if ((!j.ObjectProperty.check(prop) && !j.Property.check(prop)) ||prop.computed@@ -239,14 +244,14 @@ function buildMigratedComponents(j, oldComponents) {}/** Build `{ components: <obj> }` for `experimental.xle`. */-function buildXleObject(j, migratedComponents) {+function buildXleObject(/** @type {any} */ j, /** @type {any} */ migratedComponents) {return j.objectExpression([j.objectProperty(j.identifier('components'), migratedComponents),]);}/** Clone a property key node so we don't reuse a node across the tree. */-function cloneKey(j, key) {+function cloneKey(/** @type {any} */ j, /** @type {any} */ key) {if (j.Identifier.check(key)) return j.identifier(key.name);if (j.StringLiteral.check(key)) return j.stringLiteral(key.value);if (j.Literal.check(key)) return j.literal(key.value);@@ -254,7 +259,7 @@ function cloneKey(j, key) {}/** Build a fresh string literal preserving the original raw quoting if possible. */-function cloneStringLiteral(j, value) {+function cloneStringLiteral(/** @type {any} */ j, /** @type {any} */ value) {if (j.StringLiteral.check(value)) return j.stringLiteral(value.value);return j.literal(value.value);}diff --git a/packages/cli/src/codemods/transforms/v0.1.5/rename-switch-label-spacing-default-to-hug.mjs b/packages/cli/src/codemods/transforms/v0.1.5/rename-switch-label-spacing-default-to-hug.mjsindex 3a2241bfc1..2d09bcd574 100644--- a/packages/cli/src/codemods/transforms/v0.1.5/rename-switch-label-spacing-default-to-hug.mjs+++ b/packages/cli/src/codemods/transforms/v0.1.5/rename-switch-label-spacing-default-to-hug.mjs@@ -44,13 +44,18 @@ const TARGET_PROP = 'labelSpacing';/** Components whose `labelSpacing` prop accepts a SwitchLabelSpacing value. */const TARGET_COMPONENTS = new Set(['Switch']);+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);let hasChanges = false;/** Rewrite a string-literal node when it equals the old value. */- function renameStringLiteral(node) {+ function renameStringLiteral(/** @type {any} */ node) {if (!node) return false;if ((node.type === 'StringLiteral' || node.type === 'Literal') &&@@ -64,7 +69,8 @@ export default function transformer(file, api) {}/** Recursively rewrite the old value inside ternary/logical expressions. */- function renameInExpression(node) {+ /** @returns {boolean} */+ function renameInExpression(/** @type {any} */ node) {if (!node) return false;let changed = false;if (node.type === 'StringLiteral' || node.type === 'Literal') {@@ -83,12 +89,12 @@ export default function transformer(file, api) {}// --- 1. JSX attribute: labelSpacing="default" / labelSpacing={'default'} on Switch ---- root.find(j.JSXOpeningElement).forEach(path => {+ root.find(j.JSXOpeningElement).forEach((/** @type {any} */ path) => {const name = path.node.name;const componentName = name.type === 'JSXIdentifier' ? name.name : null;if (!componentName || !TARGET_COMPONENTS.has(componentName)) return;- path.node.attributes.forEach(attr => {+ path.node.attributes.forEach((/** @type {any} */ attr) => {if (attr.type !== 'JSXAttribute') return;if (!attr.name || attr.name.name !== TARGET_PROP) return;@@ -108,27 +114,27 @@ export default function transformer(file, api) {const importsTarget =root.find(j.ImportSpecifier)- .filter(p => TARGET_COMPONENTS.has(p.node.imported?.name))+ .filter((/** @type {any} */ p) => TARGET_COMPONENTS.has(p.node.imported?.name)).size() > 0;if (importsTarget) {const PropertyType = j.ObjectProperty ?? j.Property;// --- 2. Object property: { labelSpacing: 'default' } / 'default' as const ---- root.find(PropertyType, {key: {name: TARGET_PROP}}).forEach(path => {+ root.find(PropertyType, {key: {name: TARGET_PROP}}).forEach((/** @type {any} */ path) => {if (renameInExpression(path.node.value)) hasChanges = true;});// --- 3. Storybook argTypes: labelSpacing: { options: [..., 'default', ...] } ---- root.find(PropertyType, {key: {name: TARGET_PROP}}).forEach(path => {+ root.find(PropertyType, {key: {name: TARGET_PROP}}).forEach((/** @type {any} */ path) => {const value = path.node.value;if (!value || value.type !== 'ObjectExpression') return;const optionsProp = value.properties.find(- p => p.key && (p.key.name === 'options' || p.key.value === 'options'),+ (/** @type {any} */ p) => p.key && (p.key.name === 'options' || p.key.value === 'options'),);if (optionsProp && optionsProp.value.type === 'ArrayExpression') {- optionsProp.value.elements.forEach(el => {+ optionsProp.value.elements.forEach((/** @type {any} */ el) => {if (renameStringLiteral(el)) hasChanges = true;});}diff --git a/packages/cli/src/codemods/transforms/v0.1.7/migrate-table-tableprops-to-direct-props.mjs b/packages/cli/src/codemods/transforms/v0.1.7/migrate-table-tableprops-to-direct-props.mjsindex 0cf0975996..1b39c3dd6f 100644--- a/packages/cli/src/codemods/transforms/v0.1.7/migrate-table-tableprops-to-direct-props.mjs+++ b/packages/cli/src/codemods/transforms/v0.1.7/migrate-table-tableprops-to-direct-props.mjs@@ -54,7 +54,7 @@ const TODO_COMMENT =* property is not a simple liftable entry (spread, computed key, method,* getter/setter, non-string literal key).*/-function getPropertyKeyName(prop) {+function getPropertyKeyName(/** @type {any} */ prop) {if (prop.type !== 'ObjectProperty' && prop.type !== 'Property') return null;// espree-style Property nodes: skip methods and accessorsif (prop.method || (prop.kind != null && prop.kind !== 'init')) return null;@@ -70,6 +70,11 @@ function getPropertyKeyName(prop) {return null;}+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);@@ -77,7 +82,7 @@ export default function transformer(file, api) {// --- 1. Track local names for the Table import (alias-aware) ---const tableLocals = new Set();- root.find(j.ImportDeclaration).forEach((path) => {+ root.find(j.ImportDeclaration).forEach((/** @type {any} */ path) => {if (!TABLE_IMPORT_SOURCES.has(path.node.source.value)) return;for (const spec of path.node.specifiers ?? []) {if (spec.type === 'ImportSpecifier' && spec.imported.name === 'Table') {@@ -88,14 +93,14 @@ export default function transformer(file, api) {if (tableLocals.size === 0) return undefined;- function attachTodo(attr) {+ function attachTodo(/** @type {any} */ attr) {if (!attr.comments) attr.comments = [];- if (attr.comments.some((c) => c.value === TODO_COMMENT)) return;+ if (attr.comments.some((/** @type {any} */ c) => c.value === TODO_COMMENT)) return;attr.comments.push(j.commentBlock(TODO_COMMENT, false, true));hasChanges = true;}- function buildAttributeValue(valueNode) {+ function buildAttributeValue(/** @type {any} */ valueNode) {if (valueNode.type === 'StringLiteral' ||(valueNode.type === 'Literal' && typeof valueNode.value === 'string')@@ -106,14 +111,14 @@ export default function transformer(file, api) {}// --- 2. Rewrite tableProps on tracked <Table> elements ---- root.find(j.JSXOpeningElement).forEach((path) => {+ root.find(j.JSXOpeningElement).forEach((/** @type {any} */ path) => {const name = path.node.name;const componentName = name.type === 'JSXIdentifier' ? name.name : null;if (!componentName || !tableLocals.has(componentName)) return;const attrs = path.node.attributes;const tablePropsAttr = attrs.find(- (a) => a.type === 'JSXAttribute' && a.name?.name === 'tableProps',+ (/** @type {any} */ a) => a.type === 'JSXAttribute' && a.name?.name === 'tableProps',);if (!tablePropsAttr) return;@@ -135,22 +140,24 @@ export default function transformer(file, api) {// Objects containing spreads, computed keys, or methods are treated// as dynamic: no partial lift, just the TODO comment.const allSimple = obj.properties.every(- (prop) => getPropertyKeyName(prop) !== null,+ (/** @type {any} */ prop) => getPropertyKeyName(prop) !== null,);if (!allSimple) {attachTodo(tablePropsAttr);return;}+ /** @type {any[]} */const lifted = [];+ /** @type {any[]} */const kept = [];for (const prop of obj.properties) {const keyName = getPropertyKeyName(prop);const collidesWithSibling = attrs.some(- (a) => a.type === 'JSXAttribute' && a.name?.name === keyName,+ (/** @type {any} */ a) => a.type === 'JSXAttribute' && a.name?.name === keyName,);const collidesWithLifted = lifted.some(- (a) => a.name.name === keyName,+ (/** @type {any} */ a) => a.name.name === keyName,);if (!LIFTABLE_KEY_RE.test(keyName) ||diff --git a/packages/cli/src/codemods/transforms/v0.1.7/rename-table-renderprops-styles-to-xstyle.mjs b/packages/cli/src/codemods/transforms/v0.1.7/rename-table-renderprops-styles-to-xstyle.mjsindex 9d6a68a1c7..645a4a060d 100644--- a/packages/cli/src/codemods/transforms/v0.1.7/rename-table-renderprops-styles-to-xstyle.mjs+++ b/packages/cli/src/codemods/transforms/v0.1.7/rename-table-renderprops-styles-to-xstyle.mjs@@ -58,7 +58,7 @@ const RENDER_PROP_TYPES = new Set([]);/** Resolve the base type name from a TS type annotation node. */-function typeNameOf(typeAnnotation) {+function typeNameOf(/** @type {any} */ typeAnnotation) {// `x: TableRenderProps`const t = typeAnnotation?.typeAnnotation ?? typeAnnotation;if (!t) return null;@@ -68,6 +68,11 @@ function typeNameOf(typeAnnotation) {return null;}+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);@@ -77,7 +82,7 @@ export default function transformer(file, api) {// Function/arrow params: (props: TableRenderProps) => ...const renderPropBindings = new Set();- function collectParam(param) {+ function collectParam(/** @type {any} */ param) {if (param.type === 'Identifier' &&RENDER_PROP_TYPES.has(typeNameOf(param.typeAnnotation))@@ -88,19 +93,19 @@ export default function transformer(file, api) {root.find(j.Function)- .forEach((p) => (p.node.params ?? []).forEach(collectParam));+ .forEach((/** @type {any} */ p) => (p.node.params ?? []).forEach(collectParam));root.find(j.FunctionDeclaration)- .forEach((p) => (p.node.params ?? []).forEach(collectParam));+ .forEach((/** @type {any} */ p) => (p.node.params ?? []).forEach(collectParam));root.find(j.FunctionExpression)- .forEach((p) => (p.node.params ?? []).forEach(collectParam));+ .forEach((/** @type {any} */ p) => (p.node.params ?? []).forEach(collectParam));root.find(j.ArrowFunctionExpression)- .forEach((p) => (p.node.params ?? []).forEach(collectParam));+ .forEach((/** @type {any} */ p) => (p.node.params ?? []).forEach(collectParam));// Variable declarations: `const rp: BodyCellRenderProps = ...`- root.find(j.VariableDeclarator).forEach((p) => {+ root.find(j.VariableDeclarator).forEach((/** @type {any} */ p) => {const id = p.node.id;if (id?.type === 'Identifier' &&@@ -119,10 +124,10 @@ export default function transformer(file, api) {// 2. A spread of a tracked render-prop binding (`{...props, styles: [...]}`)// — the common "carry the render-prop object forward, override styles"// shape. (Only counts when `renderPropBindings` is non-empty.)- function isRenderPropShapedObject(objExpr) {+ function isRenderPropShapedObject(/** @type {any} */ objExpr) {if (objExpr.type !== 'ObjectExpression') return false;const keyNames = objExpr.properties- .map((pr) =>+ .map((/** @type {any} */ pr) =>pr.type === 'ObjectProperty' || pr.type === 'Property'? pr.key?.name ?? pr.key?.value: null,@@ -133,7 +138,7 @@ export default function transformer(file, api) {}// Spread of a tracked render-prop binding.const spreadsRenderProp = objExpr.properties.some(- (pr) =>+ (/** @type {any} */ pr) =>(pr.type === 'SpreadElement' || pr.type === 'ExperimentalSpreadProperty') &&pr.argument?.type === 'Identifier' &&renderPropBindings.has(pr.argument.name),@@ -146,7 +151,7 @@ export default function transformer(file, api) {// render-prop-shaped object literals (htmlProps + styles siblings);// never touch bare `styles` in this file (too ambiguous).let touched = false;- root.find(j.ObjectExpression).forEach((p) => {+ root.find(j.ObjectExpression).forEach((/** @type {any} */ p) => {if (!isRenderPropShapedObject(p.node)) return;for (const prop of p.node.properties) {if (@@ -165,7 +170,7 @@ export default function transformer(file, api) {}// --- 2. Rewrite `<binding>.styles` member access -> `.xstyle`. ---- root.find(j.MemberExpression).forEach((p) => {+ root.find(j.MemberExpression).forEach((/** @type {any} */ p) => {const {object, property, computed} = p.node;if (computed) return;if (property?.type !== 'Identifier' || property.name !== 'styles') return;@@ -177,7 +182,7 @@ export default function transformer(file, api) {});// --- 3. Rewrite `styles:` keys on render-prop-shaped object literals. ---- root.find(j.ObjectExpression).forEach((p) => {+ root.find(j.ObjectExpression).forEach((/** @type {any} */ p) => {if (!isRenderPropShapedObject(p.node)) return;for (const prop of p.node.properties) {if (diff --git a/packages/cli/src/codemods/transforms/v0.1.8/rename-avatar-size-scale.mjs b/packages/cli/src/codemods/transforms/v0.1.8/rename-avatar-size-scale.mjsindex 29e4e4935f..d73c6aa93f 100644--- a/packages/cli/src/codemods/transforms/v0.1.8/rename-avatar-size-scale.mjs+++ b/packages/cli/src/codemods/transforms/v0.1.8/rename-avatar-size-scale.mjs@@ -80,7 +80,7 @@ const UNIQUE = new Set(['tiny', 'xsmall']);* Unwraps `'small' as const`. In non-precise contexts, ambiguous names are* skipped. Returns true when a rename occurred.*/-function renameValue(node, {precise = false} = {}) {+function renameValue(/** @type {any} */ node, {precise = false} = {}) {if (!node) return false;const target = node.type === 'TSAsExpression' ? node.expression : node;const isString =@@ -95,7 +95,7 @@ function renameValue(node, {precise = false} = {}) {}/** Extract a plain string value from a literal-ish node, or null. */-function literalString(node) {+function literalString(/** @type {any} */ node) {const target = node?.type === 'TSAsExpression' ? node.expression : node;if (target &&@@ -107,6 +107,11 @@ function literalString(node) {return null;}+/**+ * @param {import('../../../types/codemod').AstryxCodemodFile} file+ * @param {import('../../../types/codemod').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);@@ -114,7 +119,7 @@ export default function transformer(file, api) {// Track alias-aware local names for the target components.const targetLocals = new Set();- root.find(j.ImportDeclaration).forEach((path) => {+ root.find(j.ImportDeclaration).forEach((/** @type {any} */ path) => {if (!IMPORT_SOURCES.has(path.node.source.value)) return;for (const spec of path.node.specifiers ?? []) {if (@@ -128,14 +133,14 @@ export default function transformer(file, api) {if (targetLocals.size === 0) return undefined;- function renameArrayElements(node) {+ function renameArrayElements(/** @type {any} */ node) {let arr = node;if (arr.type === 'TSAsExpression') arr = arr.expression;if (arr.type !== 'ArrayExpression') return;// If the array contains a name unique to Avatar's scale (tiny/xsmall), the// whole collection is unambiguously the Avatar size enum, so it is safe to// rename the ambiguous members too. Otherwise stay conservative.- const precise = arr.elements.some((el) => UNIQUE.has(literalString(el)));+ const precise = arr.elements.some((/** @type {any} */ el) => UNIQUE.has(literalString(el)));for (const el of arr.elements) {if (renameValue(el, {precise})) hasChanges = true;}@@ -143,7 +148,7 @@ export default function transformer(file, api) {// 1. `size` JSX attributes on target components — PRECISE (component known),// so all five names, including the ambiguous ones, are renamed here.- root.find(j.JSXOpeningElement).forEach((path) => {+ root.find(j.JSXOpeningElement).forEach((/** @type {any} */ path) => {const name = path.node.name;const componentName = name.type === 'JSXIdentifier' ? name.name : null;if (!componentName || !targetLocals.has(componentName)) return;@@ -182,7 +187,7 @@ export default function transformer(file, api) {// arrays — NON-PRECISE (the component isn't known here), so only the// unique names tiny/xsmall are renamed.const PropertyType = j.ObjectProperty ?? j.Property;- root.find(PropertyType).forEach((path) => {+ root.find(PropertyType).forEach((/** @type {any} */ path) => {const key = path.node.key;const keyName =key.type === 'Identifier'@@ -204,7 +209,7 @@ export default function transformer(file, api) {// size: { control: 'select', options: ['tiny', ...] }if (value.type === 'ObjectExpression') {const optionsProp = value.properties.find(- (p) => p.key && (p.key.name === 'options' || p.key.value === 'options'),+ (/** @type {any} */ p) => p.key && (p.key.name === 'options' || p.key.value === 'options'),);if (optionsProp) renameArrayElements(optionsProp.value);}@@ -216,7 +221,7 @@ export default function transformer(file, api) {// are renamed. This avoids corrupting unrelated unions that happen to use// common words like 'medium' (e.g. a priority or breakpoint type) in a// file that also imports Avatar.- root.find(j.TSLiteralType).forEach((path) => {+ root.find(j.TSLiteralType).forEach((/** @type {any} */ path) => {if (renameValue(path.node.literal)) hasChanges = true;});@@ -225,7 +230,7 @@ export default function transformer(file, api) {// e.g. `(['tiny', 'xsmall', 'small', 'medium', 'large'] as const).map(...)`// used to render every size. The unique name proves the whole array is the// Avatar enum, so its ambiguous members can be renamed safely.- root.find(j.ArrayExpression).forEach((path) => {+ root.find(j.ArrayExpression).forEach((/** @type {any} */ path) => {renameArrayElements(path.node);});diff --git a/packages/cli/src/commands/agent-docs.mjs b/packages/cli/src/commands/agent-docs.mjsindex 48fbc13917..14d68c0e6e 100644--- a/packages/cli/src/commands/agent-docs.mjs+++ b/packages/cli/src/commands/agent-docs.mjs@@ -143,9 +143,11 @@ export function parseBlockVersion(content) {*/export function inspectAgentDocs(targetDir, installedVersion) {const version = installedVersion ?? getXdsVersion(findCoreDir(targetDir));+ /** @type {Array<{path: string, blockVersion: string|null, legacy: boolean, stale: boolean}>} */const files = [];for (const rel of discoverAgentDocs(targetDir)) {+ /** @type {string} */let content;try {content = fs.readFileSync(path.join(targetDir, rel), 'utf-8');@@ -165,9 +167,10 @@ export function inspectAgentDocs(targetDir, installedVersion) {const staleEntries = files.filter(f => f.stale);const staleFiles = staleEntries.map(f => f.path);const blockVersions = [- ...new Set(staleEntries.map(f => f.blockVersion).filter(Boolean)),+ ...new Set(staleEntries.map(f => f.blockVersion).filter(/** @returns {v is string} */ (v) => v != null)),];+ /** @type {'missing' | 'stale' | 'current'} */let status;if (files.length === 0) status = 'missing';else if (staleFiles.length > 0) status = 'stale';@@ -195,7 +198,7 @@ export function resolveAgentPaths(targetDir, agent) {return {inject: [], create: [AGENTS_MD, CLAUDE_DIR_MD]};}- const searchPaths = AGENT_PRESETS[agent];+ const searchPaths = /** @type {Record<string, string[]>} */ (AGENT_PRESETS)[agent];if (!searchPaths) {return {inject: [], create: [AGENTS_MD]};}@@ -258,6 +261,10 @@ export function detectStylingSystem(targetDir) {* `stylingSystem` tailors the custom-styling guidance to what the project has* configured (see {@link detectStylingSystem}) so the agent never reaches for a* styling path that isn't compiled here.+ *+ * @param {string} version+ * @param {{coreDir?: string|null, invocation?: string, stylingSystem?: 'stylex'|'tailwind'|'css', zh?: boolean, lang?: string}} [options]+ * @returns {string}*/export function generateCompressedIndex(version, {coreDir, invocation = getCliInvocation(), stylingSystem = 'css'} = {}) {const run = invocation;@@ -337,7 +344,7 @@ export function generateCompressedIndex(version, {coreDir, invocation = getCliInif (fs.existsSync(docsDir)) {const topics = fs.readdirSync(docsDir).map(f => f.match(/^(\w+)\.doc\.mjs$/))- .filter(Boolean)+ .filter(/** @returns {m is RegExpMatchArray} */ (m) => m != null).map(m => m[1]).sort();if (topics.length > 0) lines.push(` docs <topic> ${topics.join(', ')}`);@@ -351,6 +358,8 @@ export function generateCompressedIndex(version, {coreDir, invocation = getCliIn/*** Get Astryx version from core package.+ * @param {string|null} coreDir+ * @returns {string}*/export function getXdsVersion(coreDir) {if (coreDir) {@@ -419,6 +428,9 @@ export function injectXdsBlock(filePath, compressedIndex, {createIfMissing = fal/*** Inject or update Astryx section in AGENTS.md.* Always creates the file if it doesn't exist.+ *+ * @param {string} targetDir+ * @param {string} version*/export function injectAgentsMd(targetDir, version) {const agentsPath = path.join(targetDir, AGENTS_MD);@@ -436,6 +448,8 @@ export function injectAgentsMd(targetDir, version) {* Inject or update Astryx section in CLAUDE.md.* Only injects if CLAUDE.md already exists.*+ * @param {string} targetDir+ * @param {string} version* @returns {boolean} Whether the file was written*/export function injectClaudeMd(targetDir, version) {@@ -451,6 +465,8 @@ export function injectClaudeMd(targetDir, version) {* Remove Astryx section from a file.* If the file becomes empty (only boilerplate header remains), deletes it.*+ * @param {string} filePath+ * @param {{deleteIfEmpty?: boolean}} [options]* @returns {boolean} Whether the Astryx section was found and removed*/export function removeXdsBlock(filePath, {deleteIfEmpty = false} = {}) {@@ -487,6 +503,7 @@ export function removeXdsBlock(filePath, {deleteIfEmpty = false} = {}) {/*** Remove Astryx section from all known agent doc files.+ * @param {string} targetDir*/export function removeAgentDocs(targetDir) {const allPaths = discoverAgentDocs(targetDir);@@ -528,6 +545,7 @@ export function installAgentDocs(targetDir, {zh = false, lang, agent, paths, onlconst invocation = getCliInvocation(targetDir);const stylingSystem = detectStylingSystem(targetDir);const compressedIndex = generateCompressedIndex(version, {coreDir, zh, lang, invocation, stylingSystem});+ /** @type {string[]} */const written = [];// Explicit paths override everything@@ -603,6 +621,7 @@ export function installAgentDocs(targetDir, {zh = false, lang, agent, paths, onlconst VALID_AGENTS = ['claude', 'cursor', 'codex', 'hermes', 'all'];+/** @param {import('commander').Command} program */export function registerAgentDocs(program) {program.command('agent-docs')@@ -610,7 +629,7 @@ export function registerAgentDocs(program) {.option('--remove', 'Remove the design system section from all agent doc files').option('--agent <tool>', 'Target tool: claude, cursor, codex, hermes, all').option('--agent-docs-path <path...>', 'Explicit file path(s) to write to')- .action(options => {+ .action(/** @param {{remove?: boolean, agent?: string, agentDocsPath?: string|string[]}} options */ options => {const targetDir = process.cwd();const coreDir = findCoreDir(targetDir);const version = getXdsVersion(coreDir);diff --git a/packages/cli/src/commands/blog.mjs b/packages/cli/src/commands/blog.mjsindex 620fb82dea..4358f70c93 100644--- a/packages/cli/src/commands/blog.mjs+++ b/packages/cli/src/commands/blog.mjs@@ -18,6 +18,39 @@ import {humanLog} from '../lib/json.mjs';import {cliError} from '../lib/cli-error.mjs';import {blog as blogApi} from '../api/blog.mjs';+/**+ * @typedef {object} BlogPost+ * @property {string} slug+ * @property {string} title+ * @property {string} [description]+ * @property {string} [date]+ * @property {string} [type]+ * @property {string[]} [authors]+ * @property {string} [link]+ * @property {string | null} [textUrl]+ */++/**+ * @typedef {object} BlogListData+ * @property {string} feedUrl+ * @property {BlogPost[]} posts+ */++/**+ * @typedef {BlogPost & {feedUrl: string, text: string}} BlogDetailData+ */++/**+ * @typedef {(+ * | {type: 'blog.list', data: BlogListData}+ * | {type: 'blog.detail', data: BlogDetailData}+ * )} BlogResult+ */++/**+ * @param {BlogListData} data+ * @param {string} run+ */function formatList({feedUrl, posts}, run) {const lines = [`\nAstryx blog · feed: ${feedUrl}\n`];if (posts.length === 0) {@@ -35,17 +68,25 @@ function formatList({feedUrl, posts}, run) {return lines.join('\n');}+/**+ * @param {import('commander').Command} program+ */export function registerBlog(program) {program.command('blog [slug]', {hidden: true}).description('Read the Astryx blog from the published feed')- .action(async slug => {+ .action(async (/** @type {string | undefined} */ slug) => {const run = getRunPrefix();+ /** @type {BlogResult} */let result;try {- result = await blogApi(slug);+ result = /** @type {BlogResult} */ (await blogApi(slug));} catch (e) {- cliError(e.message, {suggestions: e.suggestions || [], code: e.code});+ const err = /** @type {import('../api/error.mjs').AstryxError} */ (e);+ cliError(err.message, {+ suggestions: err.suggestions || [],+ code: err.code,+ });return;}diff --git a/packages/cli/src/commands/build-theme.mjs b/packages/cli/src/commands/build-theme.mjsindex 90a583cfbc..b41b5aed03 100644--- a/packages/cli/src/commands/build-theme.mjs+++ b/packages/cli/src/commands/build-theme.mjs@@ -32,10 +32,12 @@ import {themeAdd} from '../api/theme-add.mjs';// path: core's generator. There is no in-CLI fallback implementation — if this// import fails, the build fails (see the ERR_CORE_NOT_FOUND guard in the theme// action). A built, resolvable `@astryxdesign/core` is a hard requirement.-let _defineTheme = null;-let _generateThemeRulesSplit = null;-let _generateOnMediaCSS = null;-let _coreImportError = null;+// A built, resolvable `@astryxdesign/core` is a hard requirement. These are+// populated from a dynamic import (a runtime boundary), so `any` is intentional.+/** @type {any} */ let _defineTheme = null;+/** @type {any} */ let _generateThemeRulesSplit = null;+/** @type {any} */ let _generateOnMediaCSS = null;+/** @type {any} */ let _coreImportError = null;try {const coreTheme = await import('@astryxdesign/core/theme');_defineTheme = coreTheme.defineTheme;@@ -75,9 +77,11 @@ function generatedHeader(sourceFile, lang = 'js', command) {/*** Convert a theme name to a valid JS identifier.* e.g. 'default-minimal' → 'defaultMinimal', 'ocean' → 'ocean'+ * @param {string} name+ * @returns {string}*/function toIdentifier(name) {- return name.replace(/-([a-z])/g, (_, c) => c.toUpperCase());+ return name.replace(/-([a-z])/g, (/** @type {string} */ _, /** @type {string} */ c) => c.toUpperCase());}/**@@ -85,6 +89,9 @@ function toIdentifier(name) {* from the cwd-relative dir (most consumers import from a file under src/) but* keeps the rest of the path (e.g. `themes/gothic`). Callers note the path is* relative to the consumer's file.+ * @param {string} relDir+ * @param {string} base+ * @returns {string}*/function importSpecifier(relDir, base) {const normalized = relDir === '.' ? '' : relDir;@@ -95,11 +102,13 @@ function importSpecifier(relDir, base) {/*** Convert a kebab-case component name to PascalCase.* e.g. 'button' → 'Button', 'progress-bar' → 'ProgressBar', 'avatar-status-dot' → 'AvatarStatusDot'+ * @param {string} name+ * @returns {string}*/function toPascalCase(name) {return name.split('-')- .map(part => part.charAt(0).toUpperCase() + part.slice(1))+ .map((/** @type {string} */ part) => part.charAt(0).toUpperCase() + part.slice(1)).join('');}@@ -107,6 +116,8 @@ function toPascalCase(name) {* Load known built-in values for a component's visual props from its .doc.mjs file.* Parses the type string (e.g. "'info' | 'warning' | 'error' | 'success'") to extract values.* Returns a map of { propName: string[] } for props that are visual (listed in theming targets).+ * @param {string} componentName+ * @returns {Promise<Record<string, string[]>>}*/async function loadKnownValues(componentName) {// Resolve core src relative to the CLI package, not cwd (which may be a theme package)@@ -140,6 +151,7 @@ async function loadKnownValues(componentName) {if (allProps.length === 0) return {};// Collect visual prop names from theming targets+ /** @type {Set<string>} */const visualProps = new Set();for (const target of doc.theming.targets) {if (target.visualProps) {@@ -148,6 +160,7 @@ async function loadKnownValues(componentName) {}// Extract values from prop type strings+ /** @type {Record<string, string[]>} */const result = {};for (const prop of allProps) {if (!visualProps.has(prop.name)) continue;@@ -156,7 +169,7 @@ async function loadKnownValues(componentName) {// Parse union type: "'info' | 'warning' | 'error' | 'success'" → ['info', 'warning', 'error', 'success']const matches = prop.type.match(/'([^']+)'/g);if (matches) {- result[prop.name] = matches.map(m => m.replace(/'/g, ''));+ result[prop.name] = matches.map((/** @type {string} */ m) => m.replace(/'/g, ''));}}return result;@@ -166,12 +179,17 @@ async function loadKnownValues(componentName) {}// Cache for loaded known values+/** @type {Map<string, Record<string, string[]>>} */const _knownValuesCache = new Map();+/**+ * @param {string} componentName+ * @returns {Promise<Record<string, string[]>>}+ */async function getKnownValues(componentName) {if (!_knownValuesCache.has(componentName)) {_knownValuesCache.set(componentName, await loadKnownValues(componentName));}- return _knownValuesCache.get(componentName);+ return _knownValuesCache.get(componentName) ?? {};}/**@@ -195,10 +213,15 @@ function resolveCoreRoot() {* actually sees), falling back to the `src/<Component>/index.ts` in the* monorepo. Returns the file contents, or '' if nothing is found.*/+/** @type {Map<string, string>} */const _componentDeclCache = new Map();+/**+ * @param {string} pascalName+ * @returns {string}+ */function readComponentDeclarations(pascalName) {if (_componentDeclCache.has(pascalName)) {- return _componentDeclCache.get(pascalName);+ return _componentDeclCache.get(pascalName) ?? '';}let contents = '';const coreRoot = resolveCoreRoot();@@ -230,6 +253,9 @@ function readComponentDeclarations(pascalName) {* `HeadingType`, `ButtonSize`) are NOT augmentable, so a generated augmentation* against them is dead code. We check that the name is exported (directly or* re-exported) as a type/interface.+ * @param {string} pascalName+ * @param {string} interfaceName+ * @returns {boolean}*/function componentHasAugmentableInterface(pascalName, interfaceName) {const decl = readComponentDeclarations(pascalName);@@ -254,7 +280,7 @@ function componentHasAugmentableInterface(pascalName, interfaceName) {* generating a `declare module` block for them would be dead code — those are* skipped.*- * @param {object} themeDef - Theme definition (resolved by defineTheme)+ * @param {{components?: Record<string, Record<string, Record<string, unknown>>>}} themeDef - Theme definition (resolved by defineTheme)* @returns {Promise<string|null>} TypeScript declaration content, or null if no augmentations needed*/async function generateVariantDeclarationsAsync(themeDef) {@@ -263,6 +289,7 @@ async function generateVariantDeclarationsAsync(themeDef) {}// Collect custom values: { component: { prop: [value, ...] } }+ /** @type {Record<string, Record<string, Set<string>>>} */const customValues = {};for (const [component, rules] of Object.entries(themeDef.components)) {@@ -336,6 +363,8 @@ async function generateVariantDeclarationsAsync(themeDef) {/*** Resolve a token value — [light, dark] tuple becomes light-dark()+ * @param {unknown} value+ * @returns {unknown}*/function resolveTokenValue(value) {if (Array.isArray(value)) {@@ -347,12 +376,14 @@ function resolveTokenValue(value) {// Theme @scope selector helpers. Keep the `astryx` literal in sync with// packages/core/src/naming.ts (NAMESPACE) and generateThemeRules.ts.// Theme scopes to data-astryx-theme; the static build path must match.-const themeScopeStart = name => `[data-astryx-theme="${name}"]`;+const themeScopeStart = (/** @type {string} */ name) => `[data-astryx-theme="${name}"]`;const THEME_SCOPE_TO = `[data-astryx-theme]`;/*** Import a theme module using jiti and find the defineTheme() result.* Returns the resolved DefinedTheme object.+ * @param {string} filePath+ * @returns {Promise<any>}*/async function importThemeModule(filePath) {const jiti = createJiti(import.meta.url, {@@ -376,6 +407,10 @@ async function importThemeModule(filePath) {);}+/**+ * @param {any} value+ * @returns {boolean}+ */function isThemeObject(value) {return (value &&@@ -389,6 +424,8 @@ function isThemeObject(value) {/*** Extract the theme definition from a JS/TS file.* Tries jiti first (full TS support), falls back to regex+eval.+ * @param {string} filePath+ * @returns {Promise<any>}*/async function extractThemeDefinition(filePath) {try {@@ -397,8 +434,9 @@ async function extractThemeDefinition(filePath) {try {return extractThemeDefinitionLegacy(filePath);} catch {+ const je = /** @type {Error} */ (jitiError);throw new Error(- `Failed to load theme from ${filePath}: ${jitiError.message}\n` ++ `Failed to load theme from ${filePath}: ${je.message}\n` +`Make sure all imports in the theme file are resolvable.`,);}@@ -408,6 +446,8 @@ async function extractThemeDefinition(filePath) {/*** Fallback extraction via regex + eval.* Only works for plain object literals — can't follow imports or variables.+ * @param {string} filePath+ * @returns {any}*/function extractThemeDefinitionLegacy(filePath) {const content = fs.readFileSync(filePath, 'utf8');@@ -433,8 +473,9 @@ function extractThemeDefinitionLegacy(filePath) {return eval(`(${objStr})`);} catch (e) {+ const err = /** @type {Error} */ (e);throw new Error(- `Failed to parse theme definition in ${filePath}: ${e.message}\n` ++ `Failed to parse theme definition in ${filePath}: ${err.message}\n` +`Make sure the defineTheme() argument is a plain object literal.`,{cause: e},);@@ -448,6 +489,8 @@ function extractThemeDefinitionLegacy(filePath) {* Looks for patterns like:* import { defaultIconRegistry } from './icons';* icons: defaultIconRegistry,+ * @param {string} filePath+ * @returns {{exportName: string, importPath: string} | null}*/function extractIconInfo(filePath) {const content = fs.readFileSync(filePath, 'utf8');@@ -456,7 +499,7 @@ function extractIconInfo(filePath) {const iconsMatch = content.match(/icons:\s*([a-zA-Z_][a-zA-Z0-9_]*)/);if (!iconsMatch) return null;- const varName = iconsMatch[1];+ const varName = /** @type {string} */ (iconsMatch[1]);// Find the import for that variableconst importRegex = new RegExp(@@ -467,7 +510,7 @@ function extractIconInfo(filePath) {return {exportName: varName,- importPath: importMatch[1],+ importPath: /** @type {string} */ (importMatch[1]),};}@@ -475,6 +518,9 @@ function extractIconInfo(filePath) {* Generate a minimal JS module for a built theme.* Includes the theme name, marker, and re-exports the icon registry.* All styling is in the CSS file.+ * @param {any} themeDef+ * @param {{exportName: string, importPath: string} | null} iconInfo+ * @returns {string}*/function generateBuiltModule(themeDef, iconInfo) {const iconImport = iconInfo@@ -486,6 +532,7 @@ function generateBuiltModule(themeDef, iconInfo) {: '';// Resolve token values — tuples become light-dark() strings+ /** @type {Record<string, unknown>} */const resolvedTokens = {};if (themeDef.tokens) {for (const [key, value] of Object.entries(themeDef.tokens)) {@@ -516,6 +563,10 @@ ${iconReExport}`;/*** Generate TypeScript declarations for a built theme module.+ * @param {any} themeDef+ * @param {{exportName: string, importPath: string} | null} iconInfo+ * @param {string | null} variantsFileName+ * @returns {string}*/function generateBuiltTypes(themeDef, iconInfo, variantsFileName) {const iconType = iconInfo@@ -543,6 +594,7 @@ ${iconType}export declare const ${toIdentifier(themeDef.name)}Theme: DefinedThem/*** Known Astryx component names and their visual props.* Used to warn on typos in defineTheme component overrides.+ * @type {Record<string, string[]>}*/const KNOWN_COMPONENTS = {appshell: ['position'],@@ -604,8 +656,11 @@ const KNOWN_COMPONENTS = {* Validate component overrides in a theme definition.* Warns on unknown component names and unknown prop names.* Returns array of warning strings.+ * @param {{components?: Record<string, Record<string, unknown>>}} themeDef+ * @returns {string[]}*/function validateComponentOverrides(themeDef) {+ /** @type {string[]} */const warnings = [];if (!themeDef.components) return warnings;@@ -668,8 +723,11 @@ function validateComponentOverrides(themeDef) {* (e.g. borderRadius, padding) instead.** Returns array of error strings.+ * @param {{components?: Record<string, Record<string, Record<string, unknown>>>}} themeDef+ * @returns {string[]}*/function validatePrivateVars(themeDef) {+ /** @type {string[]} */const errors = [];if (!themeDef.components) return errors;@@ -706,14 +764,14 @@ function resolveCliBin() {* Resolves with the child's exit code; never rejects.** @param {string} file - The theme file argument, as the user passed it.- * @param {object} options - Parsed command options (only `out` is forwarded).+ * @param {{out?: string}} options - Parsed command options (only `out` is forwarded).* @returns {Promise<number>}*/function runThemeBuildOnceChild(file, options) {const cliBin = resolveCliBin();const args = [cliBin, 'theme', 'build', file];if (options.out) args.push('--out', options.out);- return new Promise(resolve => {+ return new Promise((/** @type {(code: number) => void} */ resolve) => {const child = spawn(process.execPath, args, {stdio: 'inherit',env: process.env,@@ -732,7 +790,7 @@ function runThemeBuildOnceChild(file, options) {** @param {string} file - The theme file argument, as the user passed it.* @param {string} filePath - Absolute path to the theme file.- * @param {object} options - Parsed command options.+ * @param {{out?: string}} options - Parsed command options.* @returns {Promise<void>} Resolves when the watcher is stopped (Ctrl-C).*/async function runThemeBuildWatch(file, filePath, options) {@@ -745,7 +803,8 @@ async function runThemeBuildWatch(file, filePath, options) {let building = false;let queued = false;- let debounce = null;+ /** @type {ReturnType<typeof setTimeout> | undefined} */+ let debounce;const rebuild = async () => {if (building) {@@ -776,7 +835,7 @@ async function runThemeBuildWatch(file, filePath, options) {debounce = setTimeout(rebuild, 100);});- await new Promise(resolve => {+ await new Promise((/** @type {(value?: void) => void} */ resolve) => {const stop = () => {clearTimeout(debounce);watcher.close();@@ -788,11 +847,14 @@ async function runThemeBuildWatch(file, filePath, options) {});}+/**+ * @param {import('commander').Command} program+ */export function registerTheme(program) {const theme = program.command('theme').description('Theme tools — build, export, and manage themes')- .action((options, cmd) => {+ .action((/** @type {unknown} */ options, /** @type {import('commander').Command} */ cmd) => {// Parent group has no default behaviour. If the user passed an// unknown subcommand (e.g. `astryx theme bogus`), Commander hands it to// us as a positional in cmd.args — exit 1 with a clear error.@@ -816,7 +878,7 @@ export function registerTheme(program) {'-w, --watch','Rebuild automatically when the theme file changes (Ctrl-C to stop)',)- .action(async (file, options) => {+ .action(async (/** @type {string} */ file, /** @type {{out?: string, watch?: boolean}} */ options) => {const filePath = path.resolve(process.cwd(), file);const json = program.opts().json || false;@@ -846,7 +908,8 @@ export function registerTheme(program) {try {themeDef = await extractThemeDefinition(filePath);} catch (e) {- cliError(e.message, {code: ERROR_CODES.ERR_THEME_LOAD});+ const err = /** @type {Error} */ (e);+ cliError(err.message, {code: ERROR_CODES.ERR_THEME_LOAD});return;}@@ -992,7 +1055,10 @@ export function registerTheme(program) {const augmentationSource = resolvedTheme || themeDef;const variantDecl = await generateVariantDeclarationsAsync(augmentationSource);const variantsFileName = variantDecl ? `${baseName}.variants.d.ts` : null;- const variantDtsPath = variantDecl ? path.join(outDir, variantsFileName) : null;+ const variantDtsPath =+ variantDecl && variantsFileName+ ? path.join(outDir, variantsFileName)+ : null;const variantContent = variantDecl? generatedHeader(sourceRelative, 'ts', buildCommand) + variantDecl: null;@@ -1013,11 +1079,12 @@ export function registerTheme(program) {{dest: jsPath, content: jsContent},{dest: dtsPath, content: dtsContent},];- if (variantDtsPath) {+ if (variantDtsPath && variantContent) {writes.push({dest: variantDtsPath, content: variantContent});}fs.mkdirSync(outDir, {recursive: true});+ /** @type {Array<{tmp: string, dest: string}>} */const staged = [];try {for (const w of writes) {@@ -1033,7 +1100,7 @@ export function registerTheme(program) {for (const s of staged) {try { fs.rmSync(s.tmp, {force: true}); } catch { /* best-effort */ }}- const msg = `Failed to write theme outputs: ${err.message}`;+ const msg = `Failed to write theme outputs: ${/** @type {Error} */ (err).message}`;cliError(msg, {code: ERROR_CODES.ERR_WRITE_FAILED});return;}@@ -1044,7 +1111,7 @@ export function registerTheme(program) {humanLog(` ${size} KB`);humanLog(`✓ ${path.relative(process.cwd(), jsPath)}`);humanLog(`✓ ${path.relative(process.cwd(), dtsPath)}`);- if (variantDtsPath) {+ if (variantDtsPath && variantDecl) {const augCount = (variantDecl.match(/': true;/g) || []).length;humanLog(`✓ ${path.relative(process.cwd(), variantDtsPath)} (${augCount} type augmentations)`);}@@ -1060,7 +1127,7 @@ export function registerTheme(program) {css: path.relative(process.cwd(), outPath),js: path.relative(process.cwd(), jsPath),dts: path.relative(process.cwd(), dtsPath),- ...(variantDecl ? {variantsDts: path.relative(process.cwd(), variantDtsPath)} : {}),+ ...(variantDecl && variantDtsPath ? {variantsDts: path.relative(process.cwd(), variantDtsPath)} : {}),},warnings: warningMessages,});@@ -1107,15 +1174,21 @@ Or with a <link> tag:.description('List themes available to add').action(async () => {const json = program.opts().json || false;+ /** @type {import('../types/theme').ThemeListResponse} */let result;try {- result = await themeAdd(undefined, {list: true, cwd: process.cwd()});+ result = /** @type {import('../types/theme').ThemeListResponse} */ (+ await themeAdd(undefined, {list: true, cwd: process.cwd()})+ );} catch (e) {- cliError(e.message, {suggestions: e.suggestions || [], code: e.code});+ const err = /** @type {import('../api/error.mjs').AstryxError} */ (e);+ cliError(err.message, {suggestions: err.suggestions || [], code: err.code});return;}- if (json) return jsonOut(result.type, result.data);+ // theme.list is not registered in CLIResponseType (base.d.ts, owned by the+ // coordinator) — cast the discriminant until it is added there.+ if (json) return jsonOut(/** @type {any} */ (result.type), result.data);const themes = result.data;if (themes.length === 0) {@@ -1137,26 +1210,32 @@ Or with a <link> tag:.description('Scaffold a theme into your project as editable source').option('-f, --overwrite', 'Overwrite existing files without prompting').option('--list', 'List available themes')- .action(async (slug, targetPath, options) => {+ .action(async (/** @type {string | undefined} */ slug, /** @type {string | undefined} */ targetPath, /** @type {{list?: boolean, overwrite?: boolean}} */ options) => {const json = program.opts().json || false;// The CLI is non-interactive: never prompt to confirm an overwrite.// Existing files require an explicit --overwrite; otherwise themeAdd's// ERR_FILE_EXISTS guard rejects the write.+ /** @type {import('../types/theme').ThemeListResponse | import('../types/theme').ThemeAddResponse} */let result;try {- result = await themeAdd(slug, {- list: options.list,- targetPath,- overwrite: options.overwrite,- cwd: process.cwd(),- });+ result = /** @type {import('../types/theme').ThemeListResponse | import('../types/theme').ThemeAddResponse} */ (+ await themeAdd(slug, {+ list: options.list,+ targetPath,+ overwrite: options.overwrite,+ cwd: process.cwd(),+ })+ );} catch (e) {- cliError(e.message, {suggestions: e.suggestions || [], code: e.code});+ const err = /** @type {import('../api/error.mjs').AstryxError} */ (e);+ cliError(err.message, {suggestions: err.suggestions || [], code: err.code});return;}- if (json) return jsonOut(result.type, result.data);+ // theme.list/theme.add are not registered in CLIResponseType (base.d.ts,+ // owned by the coordinator) — cast the discriminant until they are added.+ if (json) return jsonOut(/** @type {any} */ (result.type), result.data);if (result.type === 'theme.list') {const themes = result.data;diff --git a/packages/cli/src/commands/build.mjs b/packages/cli/src/commands/build.mjsindex e83753e889..2eb7515c41 100644--- a/packages/cli/src/commands/build.mjs+++ b/packages/cli/src/commands/build.mjs@@ -40,7 +40,10 @@ const FOUNDATION = [];const ALWAYS = new Set([...FRAME, ...FOUNDATION]);-/** Print the build playbook (shown when `build` is run with no query). */+/**+ * Print the build playbook (shown when `build` is run with no query).+ * @param {string} run - The CLI invocation prefix (e.g. `npx astryx`).+ */function printPlaybook(run) {const lines = ['',@@ -71,6 +74,9 @@ function printPlaybook(run) {for (const l of lines) humanLog(l);}+/**+ * @param {import('commander').Command} program+ */export function registerBuild(program) {program.command('build [query]')@@ -78,7 +84,7 @@ export function registerBuild(program) {.option('--type <domain>', 'Filter the kit to one domain (component|hook|template)').option('--limit <n>', 'Max candidates to draw from (default 60)').option('--detail', 'Verbose output (include import paths and match reason)')- .action(async (query, options) => {+ .action(async (/** @type {string | undefined} */ query, /** @type {{type?: import('../types/search').SearchDomain, limit?: string, detail?: boolean}} */ options) => {const run = getCliInvocation();const json = program.opts().json || false;@@ -100,11 +106,15 @@ export function registerBuild(program) {limit = parsed;}+ /** @type {import('../types/search').SearchResponse} */let result;try {- result = await searchApi(query, {cwd: process.cwd(), type: options.type, limit});+ result = /** @type {import('../types/search').SearchResponse} */ (+ await searchApi(query, {cwd: process.cwd(), type: options.type, limit})+ );} catch (e) {- cliError(e.message, {suggestions: e.suggestions});+ const err = /** @type {import('../api/error.mjs').AstryxError} */ (e);+ cliError(err.message, {suggestions: err.suggestions});return;}@@ -133,7 +143,7 @@ export function registerBuild(program) {.slice(0, 6);const directMatch = pages.length > 0 && pages[0].score >= PAGE_DIRECT;- const printItem = (r, label) => {+ const printItem = (/** @type {import('../types/search').SearchResultEntry} */ r, /** @type {string} */ label) => {const display = r.domain === 'template' && r.displayName ? r.displayName : r.name;humanLog('');humanLog(` [${label}] ${display}`);diff --git a/packages/cli/src/commands/component/index.mjs b/packages/cli/src/commands/component/index.mjsindex f8e1c94b9d..076b49b415 100644--- a/packages/cli/src/commands/component/index.mjs+++ b/packages/cli/src/commands/component/index.mjs@@ -27,6 +27,26 @@ import {findRelatedBlocks} from '../../api/template.mjs';import {Project} from '../../lib/project.mjs';import {warnOnIntegrationIssues} from '../../lib/integration-warnings.mjs';+/**+ * The api layer's component() widens its return to `{type: string, data: unknown}`,+ * so annotate the command-local result with the precise discriminated union from+ * src/types/component to get narrowing + typed data.+ *+ * @typedef {(+ * | import('../../types/component').ComponentListResponse+ * | import('../../types/component').ComponentBriefResponse+ * | import('../../types/component').ComponentFullResponse+ * | import('../../types/component').ComponentDetailResponse+ * | import('../../types/component').ComponentDetailPropsResponse+ * | import('../../types/component').ComponentDetailSourceResponse+ * | import('../../types/component').ComponentDetailShowcaseResponse+ * | import('../../types/component').ComponentDetailBlocksResponse+ * )} ComponentResult+ */++/**+ * @param {import('commander').Command} program+ */export function registerComponent(program) {program.command('component [name]')@@ -38,7 +58,7 @@ export function registerComponent(program) {.option('--showcase', 'Print showcase source code').option('--blocks', 'List example blocks: showcase, examples, and related').option('--package <name>', 'Scope lookup to an external package (e.g. @acme/xds-widgets)')- .action(async (name, options) => {+ .action(async (/** @type {string | undefined} */ name, /** @type {{list?: boolean, category?: string, props?: boolean, source?: boolean, showcase?: boolean, blocks?: boolean, package?: string}} */ options) => {const run = getCliInvocation();const zh = program.opts().zh || false;const dense = program.opts().dense || false;@@ -67,9 +87,10 @@ export function registerComponent(program) {// Never let the nudge break the command.}+ /** @type {ComponentResult} */let result;try {- result = await componentApi(name, {+ result = /** @type {ComponentResult} */ (await componentApi(name, {cwd: process.cwd(),list: options.list,category: options.category,@@ -80,16 +101,19 @@ export function registerComponent(program) {blocks: options.blocks,detail,lang, zh, dense,- });+ }));} catch (e) {- cliError(e.message, {suggestions: e.suggestions, code: e.code});+ const err = /** @type {import('../../api/error.mjs').AstryxError} */ (e);+ cliError(err.message, {suggestions: err.suggestions, code: err.code});return;}if (json) return jsonOut(result.type, result.data);// ── Text output ────────────────────────────────────────────- const coreDir = findCoreDir(process.cwd());+ // The api layer already resolved against core (result exists), so core is+ // present on this path; narrow away the null branch findCoreDir allows.+ const coreDir = /** @type {string} */ (findCoreDir(process.cwd()));const themeData = resolveTheme(process.cwd());switch (result.type) {@@ -101,6 +125,7 @@ export function registerComponent(program) {const CORE_PKG = '@astryxdesign/core';// Names that appear under more than one package across the whole// listing — these must always be package-qualified to disambiguate.+ /** @type {Map<string, Set<string>>} */const nameCounts = new Map();for (const items of Object.values(result.data)) {for (const item of items) {@@ -109,7 +134,9 @@ export function registerComponent(program) {nameCounts.set(item.name, set);}}+ /** @param {string} n */const isCollision = n => (nameCounts.get(n)?.size ?? 0) > 1;+ /** @param {import('../../types/component').ComponentListEntry} item */const pkgSuffix = item => {if (item.package !== CORE_PKG) return ` [${item.package}]`;if (isCollision(item.name)) return ` [${item.package}]`;diff --git a/packages/cli/src/commands/discover.mjs b/packages/cli/src/commands/discover.mjsindex 62e27a554a..aadb6cbed5 100644--- a/packages/cli/src/commands/discover.mjs+++ b/packages/cli/src/commands/discover.mjs@@ -16,12 +16,20 @@ import {cliError} from '../lib/cli-error.mjs';import {discover as discoverApi} from '../api/discover.mjs';import {getCliInvocation} from '../utils/package-manager.mjs';+/**+ * @param {import('commander').Command} program+ */export function registerDiscover(program) {program.command('discover [query]').description('Discover external packages and components').option('--components', 'List components only')- .action(async (query, options) => {+ .action(+ /**+ * @param {string | undefined} query+ * @param {{components?: boolean}} options+ */+ async (query, options) => {const detail = program.opts().detail || 'full';const json = program.opts().json || false;const lang = program.opts().lang || null;@@ -32,7 +40,8 @@ export function registerDiscover(program) {try {result = await discoverApi(query, {components: options.components, lang, zh});} catch (e) {- cliError(e.message, {suggestions: e.suggestions, code: e.code});+ const err = /** @type {import('../api/error.mjs').AstryxError} */ (e);+ cliError(err.message, {suggestions: err.suggestions, code: err.code});return;}@@ -40,7 +49,7 @@ export function registerDiscover(program) {// Forward optional meta (e.g. configured flag for discover.list) as a// sibling of data via jsonOut, so the envelope still carries// apiVersion and goes through the single sanctioned emit path.- return jsonOut(result.type, result.data, result.meta);+ return jsonOut(result.type, result.data, 'meta' in result ? result.meta : undefined);}switch (result.type) {diff --git a/packages/cli/src/commands/docs.mjs b/packages/cli/src/commands/docs.mjsindex 154000fb91..f0613e98cb 100644--- a/packages/cli/src/commands/docs.mjs+++ b/packages/cli/src/commands/docs.mjs@@ -19,6 +19,11 @@ import {docs as docsApi} from '../api/docs.mjs';// ─── Formatting ──────────────────────────────────────────────────────────────+/**+ * @param {string[]} headers+ * @param {string[][]} rows+ * @returns {string}+ */function formatTable(headers, rows) {const widths = headers.map((h, i) =>Math.max(h.length, ...rows.map(r => (r[i] || '').length)),@@ -31,10 +36,20 @@ function formatTable(headers, rows) {return `${head}\n${sep}\n${body}`;}+/**+ * @param {string[]} headers+ * @param {string[][]} rows+ * @returns {string}+ */function formatTableCompact(headers, rows) {return rows.map(r => r.join(' = ')).join('\n');}+/**+ * @param {import('../../../core/src/docs-types').ContentBlock} block+ * @param {'full' | 'compact' | 'brief'} detail+ * @returns {string | null}+ */function formatBlock(block, detail) {switch (block.type) {case 'prose':@@ -60,7 +75,7 @@ function formatBlock(block, detail) {return formatTable(block.headers, block.rows);case 'list': {- const prefix = block.style === 'ordered' ? (i) => `${i + 1}. `+ const prefix = block.style === 'ordered' ? (/** @type {number} */ i) => `${i + 1}. `: block.style === 'dont' ? () => '❌ ': block.style === 'do' ? () => '✓ ': () => '- ';@@ -72,6 +87,11 @@ function formatBlock(block, detail) {}}+/**+ * @param {import('../../../core/src/docs-types').ReferenceSection} section+ * @param {'full' | 'compact' | 'brief'} detail+ * @returns {string}+ */function formatSection(section, detail) {const blocks = section.content.map(b => formatBlock(b, detail))@@ -86,6 +106,11 @@ function formatSection(section, detail) {return `${heading}\n\n${blocks.join('\n\n')}`;}+/**+ * @param {import('../../../core/src/docs-types').ReferenceDoc} docs+ * @param {'full' | 'compact' | 'brief'} detail+ * @returns {string}+ */function formatReferenceFull(docs, detail) {if (detail === 'brief') {const header = `${docs.title}: ${docs.description}`;@@ -103,11 +128,14 @@ function formatReferenceFull(docs, detail) {// ─── Command ─────────────────────────────────────────────────────────────────+/**+ * @param {import('commander').Command} program+ */export function registerDocs(program) {program.command('docs [topic] [section]').description('Print reference docs')- .action(async (topic, section) => {+ .action(async (/** @type {string | undefined} */ topic, /** @type {string | undefined} */ section) => {const run = getCliInvocation();const lang = program.opts().lang || null;const zh = program.opts().zh || false;@@ -121,7 +149,8 @@ export function registerDocs(program) {} catch (e) {// docs API throws structured errors with {name, reason} suggestions —// pass them through untouched so the CLI envelope matches the API.- cliError(e.message, {suggestions: e.suggestions || [], code: e.code});+ const err = /** @type {import('../api/error.mjs').AstryxError} */ (e);+ cliError(err.message, {suggestions: err.suggestions || [], code: err.code});return;}diff --git a/packages/cli/src/commands/ensure-core-built.mjs b/packages/cli/src/commands/ensure-core-built.mjsindex ae07fd3eda..0c0858f19f 100644--- a/packages/cli/src/commands/ensure-core-built.mjs+++ b/packages/cli/src/commands/ensure-core-built.mjs@@ -40,6 +40,7 @@ const BUILD_TIMEOUT_MS = 180_000;const STALE_LOCK_MS = BUILD_TIMEOUT_MS + 20_000;const POLL_MS = 250;+/** @param {number} ms */function sleepSync(ms) {Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);}@@ -67,7 +68,7 @@ function tryAcquire() {fs.mkdirSync(LOCK_DIR);return true;} catch (err) {- if (err.code !== 'EEXIST') {+ if (/** @type {NodeJS.ErrnoException} */ (err).code !== 'EEXIST') {throw err;}if (lockIsStale()) {@@ -76,7 +77,7 @@ function tryAcquire() {fs.mkdirSync(LOCK_DIR);return true;} catch (retryErr) {- if (retryErr.code !== 'EEXIST') {+ if (/** @type {NodeJS.ErrnoException} */ (retryErr).code !== 'EEXIST') {throw retryErr;}}diff --git a/packages/cli/src/commands/hook/index.mjs b/packages/cli/src/commands/hook/index.mjsindex 84afb60b3c..57e47cda67 100644--- a/packages/cli/src/commands/hook/index.mjs+++ b/packages/cli/src/commands/hook/index.mjs@@ -19,6 +19,21 @@ import {ERROR_CODES} from '../../lib/error-codes.mjs';import {hook as hookApi} from '../../api/hook.mjs';import {findRelatedBlocks} from '../../api/template.mjs';+/**+ * The api layer's hook() widens its return to `{type: string, data: unknown}`,+ * so annotate the command-local result with the precise discriminated union from+ * src/types/hook to get narrowing + typed data.+ *+ * @typedef {(+ * | import('../../types/hook').HookListResponse+ * | import('../../types/hook').HookBriefResponse+ * | import('../../types/hook').HookFullResponse+ * | import('../../types/hook').HookDetailResponse+ * | import('../../types/hook').HookDetailParamsResponse+ * )} HookResult+ */++/** @param {import('commander').Command} program */export function registerHook(program) {program.command('hook [name]')@@ -26,7 +41,12 @@ export function registerHook(program) {.option('--list', 'List all hooks grouped by category').option('--category <category>', 'List hooks in a specific category').option('--params', 'Print only the parameters table')- .action(async (name, options) => {+ .action(+ /**+ * @param {string|undefined} name+ * @param {{list?: boolean, category?: string, params?: boolean}} options+ */+ async (name, options) => {const run = getCliInvocation();const zh = program.opts().zh || false;const lang = program.opts().lang || null;@@ -43,18 +63,20 @@ export function registerHook(program) {return;}+ /** @type {HookResult} */let result;try {- result = await hookApi(name, {+ result = /** @type {HookResult} */ (await hookApi(name, {cwd: process.cwd(),list: options.list,category: options.category,params: options.params,detail,lang, zh,- });+ }));} catch (e) {- cliError(e.message, {suggestions: e.suggestions, code: e.code});+ const err = /** @type {import('../../api/error.mjs').AstryxError} */ (e);+ cliError(err.message, {suggestions: err.suggestions, code: err.code});return;}@@ -123,6 +145,7 @@ export function registerHook(program) {}// Show related block templates from relatedComponentsconst relatedComps = result.data.relatedComponents || [];+ /** @type {import('../../api/template.mjs').DiscoveredTemplate[]} */const allBlocks = [];for (const comp of relatedComps) {const blocks = await findRelatedBlocks(comp);diff --git a/packages/cli/src/commands/init.mjs b/packages/cli/src/commands/init.mjsindex 786a55c3d3..4e4c642f32 100644--- a/packages/cli/src/commands/init.mjs+++ b/packages/cli/src/commands/init.mjs@@ -62,6 +62,10 @@ export function getNextSteps(invocation) {// ─── Feature: agents ─────────────────────────────────────────────────────────+/**+ * @param {string} targetDir+ * @param {{agent?: string, agentDocsPath?: string | string[]}} [opts]+ */function runAgents(targetDir, {agent, agentDocsPath} = {}) {try {const paths = agentDocsPath@@ -93,6 +97,10 @@ function runTheme() {// ─── Feature: template ───────────────────────────────────────────────────────+/**+ * @param {string} targetDir+ * @param {{templateName?: string}} [opts]+ */function runTemplate(targetDir, {templateName} = {}) {const templates = listTemplates();if (templates.length === 0) return;@@ -124,6 +132,9 @@ function runTemplate(targetDir, {templateName} = {}) {// ─── Command ─────────────────────────────────────────────────────────────────+/**+ * @param {import('commander').Command} program+ */export function registerInit(program) {program.command('init')@@ -133,7 +144,7 @@ export function registerInit(program) {.option('--remove-agents', 'Remove AI agent docs from all agent doc files').option('--agent <tool>', 'Target AI tool for agent docs: claude, cursor, codex, hermes, all').option('--agent-docs-path <path...>', 'Explicit file path(s) for agent docs')- .action((options) => {+ .action((/** @type {{features?: string, all?: boolean, removeAgents?: boolean, agent?: string, agentDocsPath?: string | string[]}} */ options) => {const targetDir = process.cwd();// Remove mode@@ -147,7 +158,7 @@ export function registerInit(program) {if (options.features || options.all) {const features = options.all? VALID_FEATURES- : options.features.split(',').map(f => f.trim().toLowerCase());+ : /** @type {string} */ (options.features).split(',').map(f => f.trim().toLowerCase());const invalid = features.filter(f => !VALID_FEATURES.includes(f));if (invalid.length > 0) {diff --git a/packages/cli/src/commands/layout.mjs b/packages/cli/src/commands/layout.mjsindex 01cda8b16a..6026eeb8da 100644--- a/packages/cli/src/commands/layout.mjs+++ b/packages/cli/src/commands/layout.mjs@@ -17,17 +17,51 @@ import {jsonOut, humanLog} from '../lib/json.mjs';import {cliError} from '../lib/cli-error.mjs';import {layoutExpand, layoutCheck, layoutGrammar} from '../api/layout.mjs';-/** Resolve the expression from arg, --file, or stdin ('-'). */-async function readExpression(expr, options) {+/**+ * The api layer's @returns for these functions widen the `type` discriminator+ * to `string`, so annotate the command-local result with the precise response+ * shapes from src/types/layout so narrowing + jsonOut typecheck.+ *+ * @typedef {import('../types/layout').LayoutExpandResponse} LayoutExpandResponse+ * @typedef {import('../types/layout').LayoutCheckResponse} LayoutCheckResponse+ * @typedef {import('../types/layout').LayoutGrammarResponse} LayoutGrammarResponse+ */++/**+ * @typedef {object} LayoutExpandOptions+ * @property {string} [file]+ * @property {'compact'|'outline'|'auto'} [form]+ * @property {string} [name]+ * @property {boolean} [loose]+ */++/**+ * @typedef {object} LayoutCheckOptions+ * @property {string} [file]+ * @property {'compact'|'outline'|'auto'} [form]+ * @property {boolean} [loose]+ */++/**+ * Resolve the expression from arg, --file, or stdin ('-').+ * @param {string} [expr]+ * @param {{file?: string}} [options]+ * @returns {Promise<string>}+ */+async function readExpression(expr, options = {}) {if (options.file) return fs.readFileSync(options.file, 'utf-8');if (expr === '-') {+ /** @type {Buffer[]} */const chunks = [];- for await (const chunk of process.stdin) chunks.push(chunk);+ for await (const chunk of process.stdin) chunks.push(/** @type {Buffer} */ (chunk));return Buffer.concat(chunks).toString('utf-8');}- return expr;+ return expr ?? '';}+/**+ * @param {import('commander').Command} program+ */export function registerLayout(program) {const layoutCmd = program.command('layout')@@ -40,24 +74,26 @@ export function registerLayout(program) {.option('--form <form>', 'Input surface: compact, outline, or auto', 'auto').option('--name <name>', 'Generated component name (PascalCase)', 'GeneratedLayout').option('--loose', 'Downgrade unknown {block} hints to TODO placeholders')- .action(async (expression, targetPath, options) => {+ .action(async (/** @type {string} */ expression, /** @type {string} */ targetPath, /** @type {LayoutExpandOptions} */ options) => {const json = program.opts().json || false;const source = await readExpression(expression, options);if (!source || source.trim() === '') {cliError('No layout expression given — pass it as an argument, via --file, or on stdin');return;}+ /** @type {LayoutExpandResponse} */let result;try {- result = await layoutExpand(source, {+ result = /** @type {LayoutExpandResponse} */ (await layoutExpand(source, {targetPath,form: options.form,loose: options.loose || false,name: options.name,cwd: process.cwd(),- });+ }));} catch (e) {- cliError(e.message, {suggestions: e.suggestions || [], code: e.code});+ const err = /** @type {import('../api/error.mjs').AstryxError} */ (e);+ cliError(err.message, {suggestions: err.suggestions || [], code: err.code});return;}if (json) return jsonOut(result.type, result.data);@@ -81,22 +117,24 @@ export function registerLayout(program) {.option('--file <file>', 'Read the expression from a file').option('--form <form>', 'Input surface: compact, outline, or auto', 'auto').option('--loose', 'Downgrade unknown {block} hints to TODO placeholders')- .action(async (expression, options) => {+ .action(async (/** @type {string} */ expression, /** @type {LayoutCheckOptions} */ options) => {const json = program.opts().json || false;const source = await readExpression(expression, options);if (!source || source.trim() === '') {cliError('No layout expression given — pass it as an argument, via --file, or on stdin');return;}+ /** @type {LayoutCheckResponse} */let result;try {- result = await layoutCheck(source, {+ result = /** @type {LayoutCheckResponse} */ (await layoutCheck(source, {form: options.form,loose: options.loose || false,cwd: process.cwd(),- });+ }));} catch (e) {- cliError(e.message, {suggestions: e.suggestions || [], code: e.code});+ const err = /** @type {import('../api/error.mjs').AstryxError} */ (e);+ cliError(err.message, {suggestions: err.suggestions || [], code: err.code});return;}if (json) return jsonOut(result.type, result.data);@@ -106,7 +144,7 @@ export function registerLayout(program) {humanLog(`\n✗ Invalid (${errors.length} error${errors.length === 1 ? '' : 's'}):`);for (const e of errors) {humanLog(` - ${e.formatted}`);- if (e.suggestions?.length > 0) humanLog(` did you mean: ${e.suggestions.join(', ')}?`);+ if (e.suggestions && e.suggestions.length > 0) humanLog(` did you mean: ${e.suggestions.join(', ')}?`);}humanLog('');process.exitCode = 1;@@ -126,11 +164,13 @@ export function registerLayout(program) {.description('Print the XLE/XLO cheatsheet (alias table generated from this branch)').action(async () => {const json = program.opts().json || false;+ /** @type {LayoutGrammarResponse} */let result;try {- result = await layoutGrammar({cwd: process.cwd()});+ result = /** @type {LayoutGrammarResponse} */ (await layoutGrammar({cwd: process.cwd()}));} catch (e) {- cliError(e.message, {suggestions: e.suggestions || [], code: e.code});+ const err = /** @type {import('../api/error.mjs').AstryxError} */ (e);+ cliError(err.message, {suggestions: err.suggestions || [], code: err.code});return;}if (json) return jsonOut(result.type, result.data);diff --git a/packages/cli/src/commands/search.mjs b/packages/cli/src/commands/search.mjsindex 245b03a8ab..45fdcf0c8f 100644--- a/packages/cli/src/commands/search.mjs+++ b/packages/cli/src/commands/search.mjs@@ -28,6 +28,9 @@ const DOMAIN_LABEL = {template: 'template',};+/**+ * @param {import('commander').Command} program+ */export function registerSearch(program) {program.command('search <query>')@@ -35,7 +38,7 @@ export function registerSearch(program) {.option('--type <domain>', `Filter to one domain (${SEARCH_DOMAINS.join('|')})`).option('--limit <n>', 'Max number of results (default 20)').option('--detail', 'Verbose output (include import paths and match reason)')- .action(async (query, options) => {+ .action(async (/** @type {string} */ query, /** @type {{type?: import('../types/search').SearchDomain, limit?: string, detail?: boolean}} */ options) => {const json = program.opts().json || false;let limit = 20;@@ -48,15 +51,19 @@ export function registerSearch(program) {limit = parsed;}+ /** @type {import('../types/search').SearchResponse} */let result;try {- result = await searchApi(query, {- cwd: process.cwd(),- type: options.type,- limit,- });+ result = /** @type {import('../types/search').SearchResponse} */ (+ await searchApi(query, {+ cwd: process.cwd(),+ type: options.type,+ limit,+ })+ );} catch (e) {- cliError(e.message, {suggestions: e.suggestions});+ const err = /** @type {import('../api/error.mjs').AstryxError} */ (e);+ cliError(err.message, {suggestions: err.suggestions});return;}diff --git a/packages/cli/src/commands/swizzle.mjs b/packages/cli/src/commands/swizzle.mjsindex 96fea435e9..9f52550626 100644--- a/packages/cli/src/commands/swizzle.mjs+++ b/packages/cli/src/commands/swizzle.mjs@@ -83,6 +83,7 @@ export function rewriteImports(content, ownerPackage = CORE_PACKAGE) {function buildFeedback(component, issuesUrl) {if (!issuesUrl) return null;+ /** @type {{issuesUrl: string, ghCommand?: string}} */const feedback = {issuesUrl};// Accept any github.com/<owner>/<repo>/issues(/new)? form.@@ -103,7 +104,7 @@ function buildFeedback(component, issuesUrl) {* empty list means "core only". The core issues URL is routed through the* Project (config.issuesUrl, falling back to the default core tracker).* @param {string} cwd- * @returns {Promise<{loadedIntegrations: Array<object>, issuesUrl: string|undefined, project: Project|null}>}+ * @returns {Promise<{loadedIntegrations: import('../lib/integrations.mjs').LoadedIntegration[], issuesUrl: string|undefined, project: Project|null}>}*/async function loadConfigSafely(cwd) {try {@@ -162,13 +163,19 @@ function resolveOwners(coreDir, loadedIntegrations, name, coreIssuesUrl) {return owners;}-/** Whether a filename should be excluded from the swizzle copy. */+/**+ * Whether a filename should be excluded from the swizzle copy.+ * @param {string} file+ */function isExcludedFromCopy(file) {return (file.includes('.test.') || file.includes('.doc.') || file === 'README.md');}+/**+ * @param {import('commander').Command} program+ */export function registerSwizzle(program) {program.command('swizzle [component]')@@ -177,7 +184,7 @@ export function registerSwizzle(program) {.option('--package <pkg>', 'Scope to a specific owning package').option('--list', 'List available components').option('-f, --overwrite', 'Overwrite existing files without prompting')- .action(async (component, options) => {+ .action(async (/** @type {string | undefined} */ component, /** @type {{output: string, package?: string, list?: boolean, overwrite?: boolean}} */ options) => {const coreDir = findCoreDir(process.cwd());const json = program.opts().json || false;const run = getCliInvocation();diff --git a/packages/cli/src/commands/template.mjs b/packages/cli/src/commands/template.mjsindex 0ced4472ed..eefb34ff50 100644--- a/packages/cli/src/commands/template.mjs+++ b/packages/cli/src/commands/template.mjs@@ -16,6 +16,34 @@ import {getCliInvocation} from '../utils/package-manager.mjs';export {discoverTemplates, listTemplates} from '../api/template.mjs';+/**+ * A template entry as produced by the discover* helpers in api/template.mjs.+ * The api layer returns these as `object[]`; this local shape captures the+ * fields the command consumes. Remove once api/template.mjs exports a precise+ * type for its discovered templates.+ * @typedef {object} DiscoveredTemplate+ * @property {'page' | 'block'} type+ * @property {string} dirName+ * @property {string} name+ * @property {string} filePath+ */++/**+ * The discriminated response returned by the template API. The api layer+ * currently declares `{type: string, data: unknown}`; narrow it here to the+ * precise union so the switch below type-checks. Replace with the api's own+ * return type once it is tightened.+ * @typedef {(+ * import('../types/template').TemplateListResponse |+ * import('../types/template').TemplateShowResponse |+ * import('../types/template').TemplateSkeletonResponse |+ * import('../types/template').TemplateCopyResponse+ * )} TemplateResponse+ */++/**+ * @param {import('commander').Command} program+ */export function registerTemplate(program) {program.command('template [name] [path]')@@ -25,7 +53,13 @@ export function registerTemplate(program) {.option('--package <pkg>', 'Narrow to templates from a specific package').option('--skeleton', 'Show layout skeleton with spatial annotations (padding, gap, nesting)').option('-f, --overwrite', 'Overwrite existing files without prompting')- .action(async (name, targetPath, options) => {+ .action(+ /**+ * @param {string | undefined} name+ * @param {string | undefined} targetPath+ * @param {{list?: boolean, type?: string, package?: string, skeleton?: boolean, overwrite?: boolean}} options+ */+ async (name, targetPath, options) => {const json = program.opts().json || false;const run = getCliInvocation();@@ -34,7 +68,12 @@ export function registerTemplate(program) {// validate-integration. Best-effort; suppressed in --json mode.try {const project = await Project.load(process.cwd());- await warnOnIntegrationIssues(project.loadedIntegrations, {json});+ await warnOnIntegrationIssues(+ /** @type {Array<import('../lib/integrations.mjs').LoadedIntegration>} */ (+ project.loadedIntegrations+ ),+ {json},+ );} catch {// Never let the nudge break the command.}@@ -59,20 +98,24 @@ export function registerTemplate(program) {}}+ /** @type {TemplateResponse} */let result;try {- result = await templateApi(name, {- list: options.list,- skeleton: options.skeleton,- type: options.type,- package: options.package,- targetPath,- cwd: process.cwd(),- });+ result = /** @type {TemplateResponse} */ (+ await templateApi(name, {+ list: options.list,+ skeleton: options.skeleton,+ type: /** @type {'page' | 'block' | undefined} */ (options.type),+ package: options.package,+ targetPath,+ cwd: process.cwd(),+ })+ );} catch (e) {// template API throws structured errors with {name, reason} suggestions —// pass them through untouched so the CLI envelope matches the API.- cliError(e.message, {suggestions: e.suggestions || [], code: e.code});+ const err = /** @type {import('../api/error.mjs').AstryxError} */ (e);+ cliError(err.message, {suggestions: err.suggestions || [], code: err.code});return;}@@ -82,6 +125,7 @@ export function registerTemplate(program) {case 'template.list': {const pages = result.data.filter(t => t.type === 'page');const blocks = result.data.filter(t => t.type === 'block');+ /** @param {import('../types/template').TemplateListEntry} t */const renderEntry = t => {const status = t.isReady ? '' : ' (WIP)';const pkg =@@ -139,12 +183,19 @@ export function registerTemplate(program) {* Path-safety enforcement happens inside the API; here we only need* enough precision to check existence — a false negative just means the* API will catch the issue and abort.+ *+ * @param {string} name+ * @param {string} targetPath+ * @returns {Promise<string | null>}*/async function detectTemplateCollision(name, targetPath) {const {discoverTemplates} = await import('../api/template.mjs');+ /** @type {DiscoveredTemplate[]} */let templates;try {- templates = await discoverTemplates(process.cwd());+ templates = /** @type {DiscoveredTemplate[]} */ (+ await discoverTemplates(process.cwd())+ );} catch {return null;}diff --git a/packages/cli/src/commands/upgrade.mjs b/packages/cli/src/commands/upgrade.mjsindex 31487e8267..920a1e606d 100644--- a/packages/cli/src/commands/upgrade.mjs+++ b/packages/cli/src/commands/upgrade.mjs@@ -82,8 +82,18 @@ function detectInstalledTargetVersion() {return null;}+/**+ * @param {(string | null | undefined | false)[] | undefined} files+ * @returns {string[]}+ */function uniqueFiles(files) {- return [...new Set((files ?? []).filter(Boolean))];+ return [+ ...new Set(+ (files ?? []).filter(+ /** @returns {f is string} */ f => Boolean(f),+ ),+ ),+ ];}/**@@ -126,14 +136,18 @@ async function runPostCodemodHooks(hooks, context, silent) {continue;}- await execFileAsync(cmd.command, cmd.args ?? [], {- cwd: cmd.options?.cwd ?? packageDir,- timeout: cmd.options?.timeout ?? 300_000,- stdio: 'pipe',- encoding: 'utf-8',- ...cmd.options,- env: {...process.env, ...(cmd.options?.env ?? {})},- });+ await execFileAsync(+ cmd.command,+ cmd.args ?? [],+ /** @type {import('node:child_process').ExecFileOptions & {encoding: 'utf-8'}} */ ({+ cwd: cmd.options?.cwd ?? packageDir,+ timeout: cmd.options?.timeout ?? 300_000,+ stdio: 'pipe',+ encoding: 'utf-8',+ ...cmd.options,+ env: {...process.env, ...(cmd.options?.env ?? {})},+ }),+ );log.success(`Post-codemod hook ${label} completed.`);}}@@ -235,8 +249,27 @@ export function refreshAgentDocs({cwd, installedVersion, apply, json}) {return summary;}+/**+ * A single core transform entry as produced by the registry manifests. The+ * registry's declared return type omits the optional `optional` flag and the+ * `pr`/`codemodType` meta fields that the transform modules actually carry;+ * this local shape captures what the upgrade command reads. Remove once+ * codemods/registry.mjs declares these fields on its return type.+ * @typedef {object} CoreTransformEntry+ * @property {string} name+ * @property {import('../types/codemod').CodemodTransform} transform+ * @property {{title: string, description?: string, pr?: string, codemodType?: string}} meta+ * @property {boolean} [optional]+ */++/**+ * A version-scoped group of core transforms from the registry.+ * @typedef {{version: string, transforms: CoreTransformEntry[]}} CoreVersionManifest+ */+/*** Register the `upgrade` command (codemod-driven version migration).+ * @param {import('commander').Command} program*/export function registerUpgrade(program) {program@@ -260,6 +293,10 @@ export function registerUpgrade(program) {.option('--integration <package-or-file>','Explicit integration package name or integration file path (repeatable)',+ /**+ * @param {string} value+ * @param {string[]} previous+ */(value, previous) => [...(previous ?? []), value],[],)@@ -270,7 +307,21 @@ export function registerUpgrade(program) {false,).option('--list', 'List available codemods', false)- .action(async options => {+ .action(+ /**+ * @param {{+ * list?: boolean,+ * from?: string,+ * apply: boolean,+ * force?: boolean,+ * codemod?: string,+ * skipCodemod?: string[],+ * integration?: string[],+ * path: string,+ * installDeps?: boolean,+ * }} options+ */+ async options => {const json = program.opts().json || false;if (!json) p.intro('Upgrade');@@ -301,7 +352,9 @@ export function registerUpgrade(program) {// over every version and re-walked getTransformsBetween('0.0.0', v),// so each codemod was printed once per release that included it// (31 unique × 9 ≈ 201 lines on the current registry).- const manifests = await getTransformsBetween('0.0.0', latestVersion);+ const manifests = /** @type {CoreVersionManifest[]} */ (+ await getTransformsBetween('0.0.0', latestVersion)+ );for (const {version, transforms} of manifests) {for (const {name, meta, optional} of transforms) {codemods.push({@@ -333,7 +386,8 @@ export function registerUpgrade(program) {return;}- const currentVersion = options.from;+ // Guarded above: reaching here means --from passed isValidSemver, so it's a string.+ const currentVersion = /** @type {string} */ (options.from);const installed = detectInstalledTargetVersion();if (!installed) {const msg =@@ -400,9 +454,9 @@ export function registerUpgrade(program) {// Resolve CORE transforms from the registry. These do not need the loaded// config. Integration codemods are discovered later, AFTER the config// loads successfully (they require a valid config to resolve).- const versionManifests = [+ const versionManifests = /** @type {CoreVersionManifest[]} */ ([...(await getTransformsBetween(currentVersion, targetVersion)),- ];+ ]);// Does the selected core set include >=1 CONFIG codemod? A config codemod// is the established convention `meta.codemodType === 'config'` (see@@ -470,6 +524,15 @@ export function registerUpgrade(program) {skipCodemods,silent: json,});+ // runCodemods returns either a success accounting or a+ // {ok: false, reason} sentinel (e.g. source_path_missing). Narrow to the+ // success shape so downstream property reads type-check; the sentinel+ // branch collapses to null and the `?? 0`/`?? []` fallbacks below treat+ // it as "no files changed", matching the existing runtime behavior.+ const coreResult =+ codemodResult && 'totalFilesChanged' in codemodResult+ ? codemodResult+ : null;// STEP 4 — Load the consumer's config (STRICT validation; unchanged). On// --apply this now sees the repaired config the core codemod just wrote.@@ -477,8 +540,11 @@ export function registerUpgrade(program) {// here. Wrap in a graceful dry-run catch (see below).// Assigned inside the try below; every catch branch returns, so these// are always set before any later read.+ /** @type {Array<import('../lib/integrations.mjs').LoadedIntegration>} */let integrations;+ /** @type {import('../types/config').PostCodemodHook[]} */let postCodemodHooks;+ /** @type {Array<{version: string, codemods: import('../types/codemod').CodemodEntry[]}>} */let integrationVersionGroups;try {const project = await Project.load(process.cwd());@@ -489,6 +555,7 @@ export function registerUpgrade(program) {]);integrations = await loadIntegrations(integrationSpecs);} catch (err) {+ const configErr = /** @type {Error} */ (err);// GRACEFUL DRY-RUN CATCH. A config that fails strict validation is the// EXPECTED, fixable case ONLY when we are in dry-run AND a pending core// config codemod just PREVIEWED a change to the config — i.e. the very@@ -499,7 +566,7 @@ export function registerUpgrade(program) {// gate and aborts below — preserving the strictness contract.) This is// the reason this PR reorders the pipeline.const codemodWouldFixConfig =- hasCoreConfigCodemod && (codemodResult?.totalFilesChanged ?? 0) > 0;+ hasCoreConfigCodemod && (coreResult?.totalFilesChanged ?? 0) > 0;if (!options.apply && codemodWouldFixConfig) {const codemodFlags = coreConfigCodemodNames.map(name => `--codemod ${name}`)@@ -518,7 +585,7 @@ export function registerUpgrade(program) {status: 'config_fixable',from: currentVersion,to: targetVersion,- configError: err.message,+ configError: configErr.message,configCodemods: coreConfigCodemodNames,suggestedCommand,message: guidance,@@ -539,11 +606,11 @@ export function registerUpgrade(program) {// refresh already ran (it's independent of config), so surface it.if (json)return jsonError(- err.message,- {agentDocs},+ configErr.message,+ /** @type {import('../types/base').Suggestion[]} */ (/** @type {unknown} */ ({agentDocs})),ERROR_CODES.ERR_INVALID_ARGUMENT,);- p.log.error(err.message);+ p.log.error(configErr.message);p.outro('Aborted');process.exitCode = 1;return;@@ -574,12 +641,21 @@ export function registerUpgrade(program) {// hard-failing the upgrade. An EXECUTION-time failure (a transform// throwing) is handled later by the codemod-error gate, which still// aborts the upgrade.+ /** @type {Map<string, Array<import('../types/codemod').CodemodEntry>>} */const integrationCodemodsByVersion = new Map();for (const integration of integrations) {if (!integration?.codemods) continue;try {const byVersion = await discoverIntegrationCodemods([integration]);- for (const [version, list] of byVersion) {+ for (const [version, rawList] of byVersion) {+ // discoverIntegrationCodemods declares `codemod: object` (loose); the+ // runtime entries carry the full CodemodEntry.codemod shape. Narrow+ // to the map's element type. Report: integration-discovery.mjs's+ // @returns should declare CodemodEntry instead of the loose object.+ const list =+ /** @type {Array<import('../types/codemod').CodemodEntry>} */ (+ /** @type {unknown} */ (rawList)+ );const existing = integrationCodemodsByVersion.get(version);if (existing) existing.push(...list);else integrationCodemodsByVersion.set(version, [...list]);@@ -589,11 +665,14 @@ export function registerUpgrade(program) {// above surfaces the underlying issue. Best-effort, non-blocking.}}- integrationVersionGroups = selectIntegrationCodemods(- integrationCodemodsByVersion,- currentVersion,- targetVersion,- );+ integrationVersionGroups =+ /** @type {Array<{version: string, codemods: import('../types/codemod').CodemodEntry[]}>} */ (+ selectIntegrationCodemods(+ integrationCodemodsByVersion,+ currentVersion,+ targetVersion,+ )+ );const hasIntegrationCodemods = integrationVersionGroups.some(g => g.codemods.length > 0,);@@ -630,7 +709,7 @@ export function registerUpgrade(program) {if (totalTransforms === 0 && totalOptional === 0) {const msg = `Codemod "${options.codemod}" not found. Use --list to see available codemods.`;if (json)- return jsonError(msg, {agentDocs}, ERROR_CODES.ERR_UNKNOWN_CODEMOD);+ return jsonError(msg, /** @type {import('../types/base').Suggestion[]} */ (/** @type {unknown} */ ({agentDocs})), ERROR_CODES.ERR_UNKNOWN_CODEMOD);p.log.error(msg);p.outro('Aborted');process.exitCode = 1;@@ -647,6 +726,26 @@ export function registerUpgrade(program) {}}+ /**+ * Terminal upgrade receipt. NOTE: the shape emitted here (with+ * `integrations`, `filesChanged`, `transformsApplied`, `errors`) is what+ * the command has always produced and what upgrade.test/config-ordering+ * assert on; it does NOT match `UpgradeRunResponse.data` in+ * types/upgrade.d.ts (which declares a stale `depsUpdated` field and omits+ * these). The jsonOut call below is cast to bridge that drift. See the+ * report: types/upgrade.d.ts needs reconciling with the real envelope.+ * @type {{+ * from: string,+ * to: string,+ * codemods: number,+ * integrations: string[],+ * agentDocsRefreshed: boolean,+ * agentDocs: import('../types/upgrade').AgentDocsSummary,+ * filesChanged?: number,+ * transformsApplied?: number,+ * errors?: Array<{file: string, codemod: string, error: string}>,+ * }}+ */const receipt = {from: currentVersion,to: targetVersion,@@ -679,17 +778,17 @@ export function registerUpgrade(program) {// Merge core + integration codemod results into a single accounting so// hooks, receipts, and error gating see both.const mergedFilesChanged =- (codemodResult?.totalFilesChanged ?? 0) ++ (coreResult?.totalFilesChanged ?? 0) +(integrationResult?.totalFilesChanged ?? 0);const mergedTransformsApplied =- (codemodResult?.totalTransformsApplied ?? 0) ++ (coreResult?.totalTransformsApplied ?? 0) +(integrationResult?.totalTransformsApplied ?? 0);const mergedWrittenFiles = [- ...(codemodResult?.writtenFiles ?? []),+ ...(coreResult?.writtenFiles ?? []),...(integrationResult?.writtenFiles ?? []),];const mergedErrors = [- ...(codemodResult?.errors ?? []),+ ...(coreResult?.errors ?? []),...(integrationResult?.errors ?? []),];@@ -714,13 +813,14 @@ export function registerUpgrade(program) {json,);} catch (err) {+ const hookErr = /** @type {Error} */ (err);if (json)return jsonError(- `Post-codemod hook failed: ${err.message}`,- {receipt},+ `Post-codemod hook failed: ${hookErr.message}`,+ /** @type {import('../types/base').Suggestion[]} */ (/** @type {unknown} */ ({receipt})),ERROR_CODES.ERR_CODEMOD_FAILED,);- p.log.error(`Post-codemod hook failed: ${err.message}`);+ p.log.error(`Post-codemod hook failed: ${hookErr.message}`);p.outro('Upgrade failed');process.exitCode = 1;return;@@ -738,7 +838,7 @@ export function registerUpgrade(program) {if (receipt.errors?.length > 0) {const msg = `Upgrade completed with ${receipt.errors.length} codemod error${receipt.errors.length === 1 ? '' : 's'}.`;if (json) {- return jsonError(msg, {receipt}, ERROR_CODES.ERR_CODEMOD_FAILED);+ return jsonError(msg, /** @type {import('../types/base').Suggestion[]} */ (/** @type {unknown} */ ({receipt})), ERROR_CODES.ERR_CODEMOD_FAILED);}p.outro('Upgrade failed');process.exitCode = 1;@@ -746,7 +846,15 @@ export function registerUpgrade(program) {}if (json) {- return jsonOut('upgrade.run', receipt);+ // The emitted receipt intentionally differs from UpgradeRunResponse.data+ // (see the typedef note above and the report): cast to the declared+ // envelope shape until types/upgrade.d.ts is reconciled.+ return jsonOut(+ 'upgrade.run',+ /** @type {import('../types/upgrade').UpgradeRunResponse['data']} */ (+ /** @type {unknown} */ (receipt)+ ),+ );}p.outro(options.apply ? 'Upgrade complete' : 'Dry run complete');});diff --git a/packages/cli/src/index.mjs b/packages/cli/src/index.mjsindex 7349505a4d..6f5fc5f0d4 100644--- a/packages/cli/src/index.mjs+++ b/packages/cli/src/index.mjs@@ -102,7 +102,7 @@ programif (extras.length > 0) {const unknown = String(extras[0]);const known = (program.commands || [])- .filter((c) => !c._hidden && c.name() !== 'help')+ .filter((c) => !(/** @type {any} */ (c)._hidden) && c.name() !== 'help').map((c) => c.name());const close = known.map((name) => ({name, distance: levenshteinDistance(unknown.toLowerCase(), name.toLowerCase())}))@@ -162,6 +162,7 @@ program*/function fullCommandName(actionCommand) {const parts = [];+ /** @type {import('commander').Command | null} */let cmd = actionCommand;while (cmd && cmd !== program) {parts.unshift(cmd.name());@@ -307,10 +308,10 @@ for (const cmd of commands) {// Command fails to load but CLI still worksprogram.command(cmd.name)- .description(`(failed to load: ${e.message})`)+ .description(`(failed to load: ${/** @type {any} */ (e).message})`).action(() => {console.error(`Command "${cmd.name}" failed to load:`);- console.error(e.message);+ console.error(/** @type {any} */ (e).message);process.exit(1);});}@@ -348,9 +349,9 @@ program.command('postinstall', {hidden: true}).action(() => {const r = getCliInvocation();- const pad = (s, len) => s + ' '.repeat(Math.max(0, len - s.length));+ const pad = (/** @type {string} */ s, /** @type {number} */ len) => s + ' '.repeat(Math.max(0, len - s.length));const W = 49; // inner width of the box- const line = (s) => ` │ ${pad(s, W)}│`;+ const line = (/** @type {string} */ s) => ` │ ${pad(s, W)}│`;console.log(`╭${'─'.repeat(W + 2)}╮${line('')}diff --git a/packages/cli/src/lib/component-discovery.mjs b/packages/cli/src/lib/component-discovery.mjsindex 019172294d..5005795ce2 100644--- a/packages/cli/src/lib/component-discovery.mjs+++ b/packages/cli/src/lib/component-discovery.mjs@@ -77,12 +77,15 @@ const HIDDEN_RE = /(?:^|\n) {0,4}hidden:\s*true/;/*** Read the `group`, `hiddenComponents`, and `hidden` fields from a* component's .doc.mjs file (synchronous).+ * @param {string} docPath+ * @returns {{group: string | null, hiddenComponents: Set<string>, hidden: boolean}}*/function readDocMeta(docPath) {try {const content = fs.readFileSync(docPath, 'utf-8');const groupMatch = GROUP_RE.exec(content);const hiddenCompsMatch = HIDDEN_COMPONENTS_RE.exec(content);+ /** @type {Set<string>} */const hiddenSet = new Set();if (hiddenCompsMatch) {for (const m of hiddenCompsMatch[1].matchAll(/['"]([^'"]+)['"]/g)) {@@ -109,13 +112,20 @@ function readDocMeta(docPath) {** Keys are sorted alphabetically (groups and ungrouped components interleaved).* Components within each group are also sorted alphabetically.+ * @param {string} coreDir+ * @returns {Record<string, string[]>}*/export function discoverComponents(coreDir) {const srcDir = path.join(coreDir, 'src');/** @type {Map<string, string|null>} componentName → group */const componentGroups = new Map();+ /**+ * @param {string} dirPath+ * @returns {string[]}+ */function collectXDSFiles(dirPath) {+ /** @type {string[]} */const results = [];if (!fs.existsSync(dirPath)) return results;const entries = fs.readdirSync(dirPath, {withFileTypes: true});@@ -185,7 +195,7 @@ export function discoverComponents(coreDir) {for (const [name, group] of componentGroups) {if (group) {if (!groups.has(group)) groups.set(group, []);- groups.get(group).push(name);+ groups.get(group)?.push(name);} else {ungrouped.push(name);}@@ -220,6 +230,9 @@ export function discoverComponents(coreDir) {* Find the .doc.mjs file for a component.* For sub-components (e.g. StackItem), returns the parent's .doc.mjs* if the sub-component is documented there.+ * @param {string} coreDir+ * @param {string} name+ * @returns {string | null}*/export function findComponentReadme(coreDir, name) {const srcDir = path.join(coreDir, 'src');@@ -278,6 +291,9 @@ export function findComponentReadme(coreDir, name) {* `useResizable.ts`), so `.ts` candidates are searched alongside `.tsx`. Without* this, deriving the import path for a `.ts`-authored function falls back to the* bare `@astryxdesign/core` root instead of its tree-shakeable subpath.+ * @param {string} coreDir+ * @param {string} name+ * @returns {string | null}*/export function findComponentSource(coreDir, name) {const srcDir = path.join(coreDir, 'src');@@ -292,6 +308,10 @@ export function findComponentSource(coreDir, name) {`${name}.ts`,];+ /**+ * @param {string} dirPath+ * @returns {string | null}+ */function searchDir(dirPath) {if (!fs.existsSync(dirPath)) return null;const entries = fs.readdirSync(dirPath, {withFileTypes: true});@@ -337,6 +357,9 @@ export function findComponentSource(coreDir, name) {/*** Compute the Levenshtein (edit) distance between two strings.* Used for fuzzy-matching component names. Dependency-free.+ * @param {string} coreDir+ * @param {string} componentName+ * @returns {string}*/export function resolveImportPath(coreDir, componentName) {const srcDir = path.join(coreDir, 'src');@@ -376,11 +399,15 @@ export function resolveImportPath(coreDir, componentName) {* Scans for *.doc.mjs files and returns their names as a flat array.** @deprecated Use discoverExternalComponentsGrouped for group-aware discovery.+ * @param {string} docsDir+ * @returns {string[]}*/export function discoverExternalComponents(docsDir) {if (!fs.existsSync(docsDir)) return [];+ /** @type {string[]} */const components = [];+ /** @param {string} dirPath */function scanDir(dirPath) {const entries = fs.readdirSync(dirPath, {withFileTypes: true});for (const entry of entries) {@@ -405,6 +432,8 @@ export function discoverExternalComponents(docsDir) {* Returns a Record<string, string[]> matching the shape of discoverComponents():* - Grouped components: `{ 'App Chrome': ['AppShell', 'SideNav', 'TopNav'] }`* - Ungrouped components: `{ 'Diff': ['Diff'] }`+ * @param {string} docsDir+ * @returns {Record<string, string[]>}*/export function discoverExternalComponentsGrouped(docsDir) {if (!fs.existsSync(docsDir)) return {};@@ -412,6 +441,7 @@ export function discoverExternalComponentsGrouped(docsDir) {/** @type {Map<string, string|null>} componentName → group */const componentGroups = new Map();+ /** @param {string} dirPath */function scanDir(dirPath) {const entries = fs.readdirSync(dirPath, {withFileTypes: true});for (const entry of entries) {@@ -440,7 +470,7 @@ export function discoverExternalComponentsGrouped(docsDir) {for (const [name, group] of componentGroups) {if (group) {if (!groups.has(group)) groups.set(group, []);- groups.get(group).push(name);+ groups.get(group)?.push(name);} else {ungrouped.push(name);}@@ -472,11 +502,18 @@ export function discoverExternalComponentsGrouped(docsDir) {/*** Find a component's doc file in an external package's docs directory.* Returns the path to {Name}.doc.mjs or null.+ * @param {string} docsDir+ * @param {string} name+ * @returns {string | null}*/export function findExternalComponentDoc(docsDir, name) {if (!fs.existsSync(docsDir)) return null;const target = `${name}.doc.mjs`;+ /**+ * @param {string} dirPath+ * @returns {string | null}+ */function scanDir(dirPath) {const entries = fs.readdirSync(dirPath, {withFileTypes: true});for (const entry of entries) {@@ -538,6 +575,7 @@ export function discoverIntegrationComponents(integration) {/** @type {Map<string, {name: string, package: string, docPath: string, sourcePath: string|null, issuesUrl: string|undefined, group: string|null}>} */const byName = new Map();+ /** @param {string} dirPath */function scanDir(dirPath) {const entries = fs.readdirSync(dirPath, {withFileTypes: true});for (const entry of entries) {@@ -582,6 +620,10 @@ export function findIntegrationComponentDoc(integration, name) {const componentsDir = integration?.components;if (!componentsDir || !fs.existsSync(componentsDir)) return null;+ /**+ * @param {string} dirPath+ * @returns {string | null}+ */function scanDir(dirPath) {const entries = fs.readdirSync(dirPath, {withFileTypes: true});// Exact same-stem match (precedence order) first in this dir.diff --git a/packages/cli/src/lib/component-format.mjs b/packages/cli/src/lib/component-format.mjsindex 7af7ff4134..4975704bfc 100644--- a/packages/cli/src/lib/component-format.mjs+++ b/packages/cli/src/lib/component-format.mjs@@ -19,15 +19,19 @@ import {getCliInvocation} from '../utils/package-manager.mjs';* Keep the `astryx-` literal in sync with packages/core/src/naming.ts* (NAMESPACE / classPrefix), the same way build-theme.mjs mirrors it.* <!-- SYNC: packages/core/src/naming.ts (namespace prefix source of truth) -->+ * @param {import('../../../core/src/docs-types').ThemingTarget} target+ * @returns {string}*/function targetKey(target) {return target.className.replace(/^astryx-/, '');}+/** @param {string} name @returns {string} */function dataAttrForName(name) {return `data-${name.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase()}`;}+/** @param {import('../../../core/src/docs-types').ThemingTarget} target @returns {string[]} */function getTargetDataAttributes(target) {return [...(target.visualProps || []).map(dataAttrForName),@@ -43,13 +47,17 @@ function getTargetDataAttributes(target) {* than the header has columns gets the excess *discarded*, so an unescaped* `gap: 0 | 0.5 | ...` silently eats its own Default and Description columns.* <!-- SYNC: packages/core/src/Markdown/parser.ts (splits on unescaped pipes) -->+ * @param {unknown} value+ * @returns {string}*/export function mdCell(value) {return String(value ?? '').replace(/\|/g, '\\|');}+/** @param {import('../../../core/src/docs-types').PropDoc[]} [props] @returns {string} */function formatPropsTable(props) {if (!props || props.length === 0) return '';+ /** @type {string[]} */const lines = [];lines.push('| Prop | Type | Default | Description |');lines.push('|------|------|---------|-------------|');@@ -72,6 +80,8 @@ function formatPropsTable(props) {* and was being printed literally as the string "undefined". Emit the* description only when present, and when there are no inline props point the* reader at the sub-component's own docs instead of a blank/`undefined` block.+ * @param {any} comp+ * @returns {string[]}*/function formatSubComponent(comp) {const out = [`### ${comp.name}\n`];@@ -92,6 +102,9 @@ function formatSubComponent(comp) {* the visualProps and the variant prop in the component's props list.* Returns an array of variant strings from the `variant` prop type,* or the variants from target visualProps.+ * @param {import('../../../core/src/docs-types').ThemingTarget} target+ * @param {any} docs+ * @returns {string[]}*/function getTargetVariants(target, docs) {if (!target.visualProps?.length) return [];@@ -99,12 +112,12 @@ function getTargetVariants(target, docs) {// If variant is a visualProp, try to resolve the actual variant values from propsif (target.visualProps.includes('variant')) {const allProps = docs.props || (docs.components?.[0]?.props) || [];- const variantProp = allProps.find(p => p.name === 'variant');+ const variantProp = allProps.find((/** @type {any} */ p) => p.name === 'variant');if (variantProp && variantProp.type.includes('|')) {return variantProp.type.replace(/['"]/g, '').split('|')- .map(v => v.trim())+ .map((/** @type {string} */ v) => v.trim()).filter(Boolean);}}@@ -115,6 +128,8 @@ function getTargetVariants(target, docs) {/*** Get the state classes for a theming target from the states field.+ * @param {import('../../../core/src/docs-types').ThemingTarget} target+ * @returns {string[]}*/function getTargetStates(target) {return target.states || [];@@ -123,13 +138,14 @@ function getTargetStates(target) {/*** Format the theming targets table, merging in theme variants if available.*- * @param {object} docs - Component doc object- * @param {object|null} themeData - Resolved theme data with variants+ * @param {any} docs - Component doc object+ * @param {any} themeData - Resolved theme data with variants* @returns {string} Markdown table*/function formatTargetsTable(docs, themeData) {if (!docs.theming?.targets?.length) return '';+ /** @type {string[]} */const lines = [];lines.push('| Component class | Preferred data attributes | Props | States |');lines.push('|-----------------|---------------------------|-------|--------|');@@ -146,7 +162,7 @@ function formatTargetsTable(docs, themeData) {// Build variant display: core variants plain, theme variants with * suffixconst variantParts = [...coreVariants,- ...themeVariants.map(v => `${v}*`),+ ...themeVariants.map((/** @type {string} */ v) => `${v}*`),];const variantsStr = variantParts.length > 0 ? variantParts.join(', ') : '—';@@ -166,12 +182,13 @@ function formatTargetsTable(docs, themeData) {/*** Format full component docs (default mode, replaces cleanReadme).*- * @param {object} docs - Component doc object+ * @param {any} docs - Component doc object* @param {object} [options] - Options- * @param {object|null} [options.themeData] - Resolved theme data+ * @param {any} [options.themeData] - Resolved theme data* @param {string|null} [options.importHint] - Import path hint (e.g. '@astryxdesign/core/Button')*/export function formatFull(docs, options = {}) {+ /** @type {string[]} */const sections = [];sections.push(`# ${docs.name}\n`);@@ -245,8 +262,8 @@ export function formatFull(docs, options = {}) {// Note about theme variants if any are presentif (themeData?.variants) {- const componentKeys = docs.theming.targets.map(t => targetKey(t));- const hasThemeVariants = componentKeys.some(k => themeData.variants[k]?.length > 0);+ const componentKeys = docs.theming.targets.map((/** @type {any} */ t) => targetKey(t));+ const hasThemeVariants = componentKeys.some((/** @type {any} */ k) => themeData.variants[k]?.length > 0);if (hasThemeVariants) {sections.push(`_\\* = custom variant from ${themeData.name || 'active'} theme_\n`);}@@ -290,7 +307,7 @@ export function formatFull(docs, options = {}) {// Component CSS vars — split into public (directly settable) and private (set via derived)if (docs.theming?.vars?.length) {- const publicVars = docs.theming.vars.filter(v => !v.private && !v.derived);+ const publicVars = docs.theming.vars.filter((/** @type {any} */ v) => !v.private && !v.derived);if (publicVars.length > 0) {sections.push('**Themeable CSS variables** — additional properties that can be overridden in `defineTheme` component overrides.\n');@@ -309,12 +326,12 @@ export function formatFull(docs, options = {}) {if (docs.theming?.derived?.length) {const varsKey = docs.theming.targets?.length ? targetKey(docs.theming.targets[0]) : docs.theming.componentKey || '';const derivedExamples = docs.theming.derived- .filter(d => d.vars?.length)- .map(d => ` ${d.property}: '...',`)+ .filter((/** @type {any} */ d) => d.vars?.length)+ .map((/** @type {any} */ d) => ` ${d.property}: '...',`).join('\n');const expandExamples = docs.theming.derived- .filter(d => d.expand === 'container')- .map(d => ` ${d.property}: '...', // expands to container layout tokens`)+ .filter((/** @type {any} */ d) => d.expand === 'container')+ .map((/** @type {any} */ d) => ` ${d.property}: '...', // expands to container layout tokens`).join('\n');const allExamples = [derivedExamples, expandExamples].filter(Boolean).join('\n');if (allExamples) {@@ -331,6 +348,10 @@ export function formatFull(docs, options = {}) {/*** Format compact docs for LLM consumption (replaces extractCompact + ensureImportStatement).* Includes: import, best practices, props, theming.+ * @param {any} docs+ * @param {string} componentName+ * @param {string} [importHint]+ * @returns {string}*/export function formatCompact(docs, componentName, importHint) {// Bare name (un-prefix migration P5a): the CLI now presents component names@@ -339,6 +360,7 @@ export function formatCompact(docs, componentName, importHint) {? componentName.slice(3): componentName;+ /** @type {string[]} */const sections = [];sections.push(`# ${docs.name}\n`);@@ -346,7 +368,7 @@ export function formatCompact(docs, componentName, importHint) {sections.push(desc + '\n');if (docs.usage?.anatomy?.length) {- sections.push('Anatomy: ' + docs.usage.anatomy.map(el => {+ sections.push('Anatomy: ' + docs.usage.anatomy.map((/** @type {any} */ el) => {const req = el.required ? '' : ' (optional)';return `${el.name}${req}`;}).join(', ') + '\n');@@ -396,7 +418,7 @@ export function formatCompact(docs, componentName, importHint) {propLines.push('| CSS Property | Sets |');propLines.push('|-------------|------|');for (const d of docs.theming.derived) {- const target = d.expand === 'container' ? 'container layout tokens' : (d.vars || []).map(v => `\`${mdCell(v)}\``).join(', ');+ const target = d.expand === 'container' ? 'container layout tokens' : (d.vars || []).map((/** @type {any} */ v) => `\`${mdCell(v)}\``).join(', ');propLines.push(`| \`${mdCell(d.property)}\` | ${target} |`);}sections.push(propLines.join('\n') + '\n');@@ -426,12 +448,20 @@ export function formatCompact(docs, componentName, importHint) {*/const SIGNATURE_UNION_MAX_MEMBERS = 8;+/**+ * @param {any} docs+ * @param {string} componentName+ * @param {string} [importHint]+ * @param {{themeData?: any}} [options]+ * @returns {string}+ */export function formatBrief(docs, componentName, importHint, options = {}) {const displayName = componentName.startsWith('XDS')? componentName.slice(3): componentName;// Find the right props and examples for this component+ /** @type {any[]} */let props = [];let description = docs.usage?.description || docs.description || '';let examples = docs.examples || [];@@ -439,7 +469,7 @@ export function formatBrief(docs, componentName, importHint, options = {}) {if ('props' in docs) {props = docs.props;} else if ('components' in docs) {- const entry = docs.components.find(c => c.name === displayName);+ const entry = docs.components.find((/** @type {any} */ c) => c.name === displayName);if (entry) {props = entry.props;description = entry.description;@@ -448,7 +478,9 @@ export function formatBrief(docs, componentName, importHint, options = {}) {}// Build signature from union-type props+ /** @type {string[]} */const signatureProps = [];+ /** @type {string[]} */const otherProps = [];for (const prop of props) {@@ -457,7 +489,7 @@ export function formatBrief(docs, componentName, importHint, options = {}) {? prop.type.replace(/['"]/g, '').split('|')- .map(v => v.trim())+ .map((/** @type {string} */ v) => v.trim()): null;if (values && values.length <= SIGNATURE_UNION_MAX_MEMBERS) {signatureProps.push(`${prop.name}: ${values.join('|')}`);@@ -469,6 +501,7 @@ export function formatBrief(docs, componentName, importHint, options = {}) {}// Build output+ /** @type {string[]} */const output = [];// Signature line@@ -490,8 +523,8 @@ export function formatBrief(docs, componentName, importHint, options = {}) {// Component vars (if any — only show public vars)if (docs.theming?.vars?.length) {const varNames = docs.theming.vars- .filter(v => !v.derived && !v.private)- .map(v => `${v.name} (${v.default})`)+ .filter((/** @type {any} */ v) => !v.derived && !v.private)+ .map((/** @type {any} */ v) => `${v.name} (${v.default})`).join(', ');if (varNames) {output.push(` Vars: ${varNames}`);@@ -501,7 +534,7 @@ export function formatBrief(docs, componentName, importHint, options = {}) {// Derived properties (if any)if (docs.theming?.derived?.length) {const derivedNames = docs.theming.derived- .map(d => d.expand === 'container' ? `${d.property} → container tokens` : `${d.property} → ${(d.vars || []).join(', ')}`)+ .map((/** @type {any} */ d) => d.expand === 'container' ? `${d.property} → container tokens` : `${d.property} → ${(d.vars || []).join(', ')}`).join('; ');output.push(` Derived: ${derivedNames}`);}@@ -509,7 +542,7 @@ export function formatBrief(docs, componentName, importHint, options = {}) {// Theme targets (component class, preferred data attrs, props, states) with theme variant mergingif (docs.theming?.targets?.length) {const { themeData = null } = options;- const targetParts = docs.theming.targets.map(t => {+ const targetParts = docs.theming.targets.map((/** @type {any} */ t) => {const parts = [t.className];const dataAttrs = getTargetDataAttributes(t);if (dataAttrs.length) parts.push(`preferred attrs: ${dataAttrs.join(', ')}`);@@ -518,7 +551,7 @@ export function formatBrief(docs, componentName, importHint, options = {}) {// Merge theme variantsconst componentKey = targetKey(t);const themeVars = themeData?.variants?.[componentKey];- if (themeVars?.length) parts.push(`theme: ${themeVars.map(v => v + '*').join(', ')}`);+ if (themeVars?.length) parts.push(`theme: ${themeVars.map((/** @type {any} */ v) => v + '*').join(', ')}`);return parts.join(' ');});output.push(` Targets: ${targetParts.join(' | ')}`);@@ -533,7 +566,7 @@ export function formatBrief(docs, componentName, importHint, options = {}) {if (examples.length > 0) {const code = examples[0].code;const codeLine =- code.split('\n').find(l => l.trim().startsWith('<XDS')) ||+ code.split('\n').find((/** @type {string} */ l) => l.trim().startsWith('<XDS')) ||code.split('\n')[0];output.push(` ${codeLine.trim()}`);}@@ -543,6 +576,9 @@ export function formatBrief(docs, componentName, importHint, options = {}) {/*** Format only the props tables (replaces extractProps).+ * @param {any} docs+ * @param {string} componentName+ * @returns {string}*/export function formatProps(docs, componentName) {if ('props' in docs) {@@ -550,6 +586,7 @@ export function formatProps(docs, componentName) {}if ('components' in docs) {+ /** @type {string[]} */const sections = [];for (const comp of docs.components) {sections.push(`### ${comp.name} Props\n`);@@ -563,9 +600,13 @@ export function formatProps(docs, componentName) {/*** Format brief summaries for ALL components in one output.+ * @param {string} coreDir+ * @param {{zh?: boolean, lang?: string, themeData?: any}} [options]+ * @returns {Promise<string>}*/export async function formatBriefAll(coreDir, {zh = false, lang, themeData = null} = {}) {const components = discoverComponents(coreDir);+ /** @type {string[]} */const output = [];for (const [key, comps] of Object.entries(components)) {diff --git a/packages/cli/src/lib/component-loader.mjs b/packages/cli/src/lib/component-loader.mjsindex d691f57837..0e8b33f3b2 100644--- a/packages/cli/src/lib/component-loader.mjs+++ b/packages/cli/src/lib/component-loader.mjs@@ -37,6 +37,7 @@ export async function loadComponentDoc({zh = false, dense = false, lang} = {},) {const mod = await importUserModule(docPath);+ /** @type {any} */const authored = mod?.default ?? mod?.docs;const result = ComponentDocSchema.safeParse(authored);@@ -52,16 +53,23 @@ export async function loadComponentDoc(locale === 'zh' ? 'docsZh' : locale === 'dense' ? 'docsDense' : null;if (!translationKey || !mod[translationKey]) return docs;+ /** @type {any} */const translation = mod[translationKey];- if (translation.props || translation.components?.some(c => c.props)) {+ if (translation.props || translation.components?.some((/** @type {any} */ c) => c.props)) {return translation;}return mergeTranslation(docs, translation);}+/**+ * @param {any} docs+ * @param {any} translation+ * @returns {any}+ */export function mergeTranslation(docs, translation) {if (!translation) return docs;+ /** @type {any} */const merged = {...docs};// Merge prose into usage@@ -77,7 +85,7 @@ export function mergeTranslation(docs, translation) {// Merge prop descriptions for single-component docsif (translation.propDescriptions && merged.props) {- merged.props = merged.props.map(prop => {+ merged.props = merged.props.map((/** @type {any} */ prop) => {const desc = translation.propDescriptions[prop.name];return desc != null ? {...prop, description: desc} : prop;});@@ -88,7 +96,7 @@ export function mergeTranslation(docs, translation) {// translation has an entry. Names may include dots (e.g. 'options.isActive');// the lookup is keyed by the exact param name.if (translation.paramDescriptions && merged.params) {- merged.params = merged.params.map(param => {+ merged.params = merged.params.map((/** @type {any} */ param) => {const desc = translation.paramDescriptions[param.name];return desc != null ? {...param, description: desc} : param;});@@ -97,7 +105,7 @@ export function mergeTranslation(docs, translation) {// Merge hook return descriptions (HookTranslationDoc). Returns are an array// of {name, type, description}; override description by name where present.if (translation.returnDescriptions && merged.returns) {- merged.returns = merged.returns.map(ret => {+ merged.returns = merged.returns.map((/** @type {any} */ ret) => {const desc = translation.returnDescriptions[ret.name];return desc != null ? {...ret, description: desc} : ret;});@@ -105,15 +113,15 @@ export function mergeTranslation(docs, translation) {// Merge sub-component translationsif (translation.components && merged.components) {- merged.components = merged.components.map((comp, i) => {- const trans = translation.components.find(t => t.name === comp.name)+ merged.components = merged.components.map((/** @type {any} */ comp, /** @type {any} */ i) => {+ const trans = translation.components.find((/** @type {any} */ t) => t.name === comp.name)|| translation.components[i];if (!trans) return comp;const mergedComp = {...comp};if (trans.description) mergedComp.description = trans.description;if (trans.propDescriptions && comp.props) {- mergedComp.props = comp.props.map(prop => {+ mergedComp.props = comp.props.map((/** @type {any} */ prop) => {const desc = trans.propDescriptions[prop.name];return desc != null ? {...prop, description: desc} : prop;});@@ -130,6 +138,9 @@ export function mergeTranslation(docs, translation) {* Supports --lang flag: 'zh' for Chinese, 'dense' for compressed format.* Also supports legacy --zh and --dense flags.* Translations are merged onto the base docs, keeping structure intact.+ * @param {string} readmePath+ * @param {{zh?: boolean, dense?: boolean, lang?: string}} [opts]+ * @returns {Promise<any>}*/export async function loadDocs(readmePath, {zh = false, dense = false, lang} = {}) {const mod = await import(pathToFileURL(readmePath).href);@@ -151,7 +162,7 @@ export async function loadDocs(readmePath, {zh = false, dense = false, lang} = {// `isIconOnly`. A reader of the translated docs cannot discover a prop that// is not there. Overlay it instead, so an untranslated prop falls back to// its English entry. (Same principle as the reference-doc overlays, #2182.)- if (translation.props || translation.components?.some(c => c.props)) {+ if (translation.props || translation.components?.some((/** @type {any} */ c) => c.props)) {return overlayComponentDoc(docs, translation);}@@ -172,11 +183,14 @@ export async function loadDocs(readmePath, {zh = false, dense = false, lang} = {* @returns {any} Merged doc with every base prop present.*/function overlayComponentDoc(docs, translation) {- /** Merge one prop list: keep base entries and order, translate what's covered. */+ /** Merge one prop list: keep base entries and order, translate what's covered.+ * @param {any[] | undefined} baseProps+ * @param {any[] | undefined} tProps+ */const overlayProps = (baseProps, tProps) => {if (!baseProps) return baseProps;- const byName = new Map((tProps ?? []).map(p => [p.name, p]));- return baseProps.map(prop => {+ const byName = new Map((tProps ?? []).map((/** @type {any} */ p) => [p.name, p]));+ return baseProps.map((/** @type {any} */ prop) => {const t = byName.get(prop.name);// Take the translated text, but never let it drop the prop's contract// (type/default/required stay authoritative from the English doc).@@ -190,9 +204,9 @@ function overlayComponentDoc(docs, translation) {if (docs.components) {const tByName = new Map(- (translation.components ?? []).map(c => [c.name, c]),+ (translation.components ?? []).map((/** @type {any} */ c) => [c.name, c]),);- merged.components = docs.components.map(base => {+ merged.components = docs.components.map((/** @type {any} */ base) => {const t = tByName.get(base.name);if (!t) return base;return {...base, ...t, props: overlayProps(base.props, t.props)};diff --git a/packages/cli/src/lib/hook-discovery.mjs b/packages/cli/src/lib/hook-discovery.mjsindex 759f0925b6..20c19bb5f5 100644--- a/packages/cli/src/lib/hook-discovery.mjs+++ b/packages/cli/src/lib/hook-discovery.mjs@@ -15,6 +15,8 @@ const CATEGORY_RE = /(?:^|\n) {0,4}category:\s*['"]([^'"]+)['"]/;/*** Read the `category` field from a hook's .doc.mjs file (synchronous).+ * @param {string} docPath+ * @returns {{category: string | null}}*/function readHookMeta(docPath) {try {@@ -31,6 +33,8 @@ function readHookMeta(docPath) {/*** Extract the hook name from a doc filename.* e.g. 'useFocusTrap.doc.mjs' → 'useFocusTrap'+ * @param {string} fileName+ * @returns {string}*/function hookNameFromFile(fileName) {return fileName.replace('.doc.mjs', '');@@ -41,6 +45,8 @@ function hookNameFromFile(fileName) {* Returns Record<category, hookName[]> similar to discoverComponents.* Categories from HookDoc.category: focus, layout, animation, interaction, data, media, streaming* Hooks without a category go in 'Other'.+ * @param {string} coreDir+ * @returns {Record<string, string[]>}*/export function discoverHooks(coreDir) {const srcDir = path.join(coreDir, 'src');@@ -77,7 +83,7 @@ export function discoverHooks(coreDir) {const groups = new Map();for (const [hookName, category] of hookCategories) {if (!groups.has(category)) groups.set(category, []);- groups.get(category).push(hookName);+ groups.get(category)?.push(hookName);}// Sort members within each group@@ -103,6 +109,8 @@ export function discoverHooks(coreDir) {/*** Recursively scan a directory for use*.doc.mjs files.+ * @param {string} dirPath+ * @param {Map<string, string>} hookCategories*/function scanDirForHookDocs(dirPath, hookCategories) {if (!fs.existsSync(dirPath)) return;@@ -199,6 +207,9 @@ export function findHookDoc(coreDir, name) {/*** Recursively search a directory for a hook doc matching any of the candidate names.+ * @param {string} dirPath+ * @param {string[]} candidates+ * @returns {string | null}*/function searchDirForHookDoc(dirPath, candidates) {if (!fs.existsSync(dirPath)) return null;@@ -221,6 +232,8 @@ function searchDirForHookDoc(dirPath, candidates) {/*** Get all discovered hook names as a flat array (for fuzzy matching).+ * @param {string} coreDir+ * @returns {string[]}*/export function getAllHookNames(coreDir) {const hooks = discoverHooks(coreDir);diff --git a/packages/cli/src/lib/hook-format.mjs b/packages/cli/src/lib/hook-format.mjsindex d13b87d688..fdb3b59044 100644--- a/packages/cli/src/lib/hook-format.mjs+++ b/packages/cli/src/lib/hook-format.mjs@@ -16,14 +16,16 @@ import {mdCell} from './component-format.mjs';/*** Build a signature string from hook docs.* e.g. 'useFocusTrap(options: UseFocusTrapOptions): { containerRef, focusFirst }'+ * @param {any} docs+ * @returns {string}*/function buildSignature(docs) {const name = docs.name;// Build params string — only top-level params (skip options.foo nested params)- const topParams = (docs.params || []).filter(p => !p.name.includes('.'));+ const topParams = (docs.params || []).filter((/** @type {any} */ p) => !p.name.includes('.'));const paramStr = topParams- .map(p => {+ .map((/** @type {any} */ p) => {const opt = p.required ? '' : '?';return `${p.name}${opt}: ${p.type}`;})@@ -37,7 +39,7 @@ function buildSignature(docs) {} else if (returns.length === 1 && returns[0].name === 'value') {returnStr = returns[0].type;} else {- returnStr = `{ ${returns.map(r => r.name).join(', ')} }`;+ returnStr = `{ ${returns.map((/** @type {any} */ r) => r.name).join(', ')} }`;}return `${name}(${paramStr}): ${returnStr}`;@@ -45,9 +47,12 @@ function buildSignature(docs) {/*** Format a parameters table (matches component props table style).+ * @param {any[]} [params]+ * @returns {string}*/function formatParamsTable(params) {if (!params || params.length === 0) return '';+ /** @type {string[]} */const lines = [];lines.push('| Param | Type | Default | Description |');lines.push('|-------|------|---------|-------------|');@@ -63,9 +68,12 @@ function formatParamsTable(params) {/*** Format a returns table.+ * @param {any[]} [returns]+ * @returns {string}*/function formatReturnsTable(returns) {if (!returns || returns.length === 0) return '';+ /** @type {string[]} */const lines = [];lines.push('| Field | Type | Description |');lines.push('|-------|------|-------------|');@@ -81,8 +89,11 @@ function formatReturnsTable(returns) {* Format full hook docs (default mode).* Matches component formatFull structure:* # Name, description, anatomy→params, best practices, props→params+returns, theming→related+ * @param {any} docs+ * @returns {string}*/export function formatHookFull(docs) {+ /** @type {string[]} */const sections = [];sections.push(`# ${docs.name}\n`);@@ -119,8 +130,12 @@ export function formatHookFull(docs) {* Format compact hook docs for LLM consumption.* Matches component formatCompact structure:* # Name, description, ## Import, ## Best Practices, ## Parameters, ## Returns+ * @param {any} docs+ * @param {string} [importPath]+ * @returns {string}*/export function formatHookCompact(docs, importPath) {+ /** @type {string[]} */const sections = [];sections.push(`# ${docs.name}\n`);@@ -159,6 +174,7 @@ export function formatHookCompact(docs, importPath) {}// Related components (compact footer)+ /** @type {string[]} */const relatedParts = [];if (docs.relatedComponents?.length) {relatedParts.push(`Components: ${docs.relatedComponents.join(', ')}`);@@ -181,8 +197,11 @@ export function formatHookCompact(docs, importPath) {* signature ← from 'import/path'* description* key params+ * @param {any} docs+ * @returns {string}*/export function formatHookBrief(docs) {+ /** @type {string[]} */const output = [];// Signature line with import hint (matches component brief)@@ -204,8 +223,8 @@ export function formatHookBrief(docs) {// Key params (matches component brief 'prop · prop' line)const paramNames = (docs.params || [])- .filter(p => !p.name.includes('.'))- .map(p => p.required ? `${p.name}: ${p.type.split('|')[0].trim()}` : p.name);+ .filter((/** @type {any} */ p) => !p.name.includes('.'))+ .map((/** @type {any} */ p) => p.required ? `${p.name}: ${p.type.split('|')[0].trim()}` : p.name);if (paramNames.length > 0) {output.push(` ${paramNames.join(' \u00b7 ')}`);}@@ -216,9 +235,12 @@ export function formatHookBrief(docs) {/*** Format brief summaries for ALL hooks in one output.* Matches component formatBriefAll: group headers with ##.+ * @param {string} coreDir+ * @returns {Promise<string>}*/export async function formatHookBriefAll(coreDir) {const hooks = discoverHooks(coreDir);+ /** @type {string[]} */const output = [];for (const [category, hookNames] of Object.entries(hooks)) {@@ -243,6 +265,8 @@ export async function formatHookBriefAll(coreDir) {/*** Format only the parameters table (matches component formatProps).+ * @param {any} docs+ * @returns {string}*/export function formatHookParams(docs) {if (docs.params?.length) {diff --git a/packages/cli/src/lib/integration-warnings.mjs b/packages/cli/src/lib/integration-warnings.mjsindex fb93b15f87..341b257780 100644--- a/packages/cli/src/lib/integration-warnings.mjs+++ b/packages/cli/src/lib/integration-warnings.mjs@@ -28,7 +28,7 @@ import {validateLoadedIntegration} from '../api/validate-integration.mjs';** Warning: <pkg> has N integration issue(s). Run: astryx validate-integration <pkg>*- * @param {Array<object>} loadedIntegrations the Project's loaded integrations+ * @param {Array<import('./integrations.mjs').LoadedIntegration>} loadedIntegrations the Project's loaded integrations* @param {{json?: boolean}} [options]* @returns {Promise<void>}*/diff --git a/packages/cli/src/lib/integrations.mjs b/packages/cli/src/lib/integrations.mjsindex 031b608159..dea7192128 100644--- a/packages/cli/src/lib/integrations.mjs+++ b/packages/cli/src/lib/integrations.mjs@@ -15,6 +15,23 @@ import * as path from 'node:path';import {AstryxIntegrationSchema} from './config-schema.mjs';import {loadModuleWithSchema, findPresentFiles} from './module-loader.mjs';+/**+ * A fully-resolved, loaded integration. Identity (`name`, `version`) comes from+ * the package's package.json; the `components`/`templates`/`codemods` roots are+ * absolute paths resolved from the manifest. The `__`-prefixed fields are+ * internal bookkeeping used by validate-integration and Project.+ * @typedef {object} LoadedIntegration+ * @property {string} name+ * @property {string} [version]+ * @property {string} [components]+ * @property {string} [templates]+ * @property {string} [codemods]+ * @property {string} [issuesUrl]+ * @property {string} __spec+ * @property {string} __packageDir+ * @property {string} __manifestFile+ */+/** Conventional manifest basenames, in load-precedence order. */export const MANIFEST_BASENAMES = ['astryx.integration.ts',@@ -85,8 +102,10 @@ function resolveManifestPath(packageDir, spec) {** @param {string[]} [specs] package names* @param {{cwd?: string}} [options]+ * @returns {Promise<LoadedIntegration[]>}*/export async function loadIntegrations(specs = [], {cwd = process.cwd()} = {}) {+ /** @type {LoadedIntegration[]} */const integrations = [];const seen = new Set();@@ -112,6 +131,7 @@ export async function loadIntegrations(specs = [], {cwd = process.cwd()} = {}) {{label: `Integration ${spec}`},);+ /** @param {string | null | undefined} value */const resolveRoot = value =>value == null ? undefined : path.resolve(packageDir, value);diff --git a/packages/cli/src/lib/json-shim.mjs b/packages/cli/src/lib/json-shim.mjsindex e35fc0cada..bf87e9c8e7 100644--- a/packages/cli/src/lib/json-shim.mjs+++ b/packages/cli/src/lib/json-shim.mjs@@ -65,6 +65,7 @@ function jsonActive() {export function buildHelpEnvelope(cmd) {// Reconstruct the fully-qualified command name (e.g. "astryx theme build").const nameParts = [];+ /** @type {import('commander').Command | null} */let c = cmd;while (c) {nameParts.unshift(c.name());@@ -81,7 +82,7 @@ export function buildHelpEnvelope(cmd) {});const subcommands = cmd.commands- .filter((s) => !s._hidden)+ .filter((s) => !(/** @type {any} */ (s))._hidden).map((s) => ({name: s.name(), description: s.description() || ''}));return {@@ -227,10 +228,14 @@ let Command_outputHelp_patched = false;* @param {import('commander').Command} cmd*/function patchOutputHelp(cmd) {- if (cmd.__xdsHelpPatched) return;- cmd.__xdsHelpPatched = true;+ // Commander instances are monkeypatched at runtime with an internal+ // `__xdsHelpPatched` marker and a replacement `outputHelp`, neither of which+ // is in commander's public types — treat the instance as untyped here.+ const anyCmd = /** @type {any} */ (cmd);+ if (anyCmd.__xdsHelpPatched) return;+ anyCmd.__xdsHelpPatched = true;const original = cmd.outputHelp.bind(cmd);- cmd.outputHelp = function patchedOutputHelp(contextOptions) {+ anyCmd.outputHelp = function patchedOutputHelp(/** @type {any} */ contextOptions) {if (jsonActive()) {if (!process.__xdsJsonHandled) {process.__xdsJsonHandled = true;@@ -254,7 +259,7 @@ function patchPrototype(CommandCtor) {if (proto.__xdsHelpPatched) return;proto.__xdsHelpPatched = true;const original = proto.outputHelp;- proto.outputHelp = function patchedProtoOutputHelp(contextOptions) {+ proto.outputHelp = function patchedProtoOutputHelp(/** @type {any} */ contextOptions) {if (jsonActive()) {if (!process.__xdsJsonHandled) {process.__xdsJsonHandled = true;diff --git a/packages/cli/src/lib/levenshtein.mjs b/packages/cli/src/lib/levenshtein.mjsindex a6b6df59d0..16635eeb77 100644--- a/packages/cli/src/lib/levenshtein.mjs+++ b/packages/cli/src/lib/levenshtein.mjs@@ -13,8 +13,14 @@* @position lib — shared by string-utils.mjs and lib/xle/validate.mjs*/+/**+ * @param {string} a+ * @param {string} b+ * @returns {number}+ */export function levenshteinDistance(a, b) {const m = a.length, n = b.length;+ /** @type {number[][]} */const dp = Array.from({length: m + 1}, () => Array(n + 1).fill(0));for (let i = 0; i <= m; i++) dp[i][0] = i;for (let j = 0; j <= n; j++) dp[0][j] = j;diff --git a/packages/cli/src/lib/manifest.mjs b/packages/cli/src/lib/manifest.mjsindex 88f9e94ca7..1b64dbdfe5 100644--- a/packages/cli/src/lib/manifest.mjs+++ b/packages/cli/src/lib/manifest.mjs@@ -103,7 +103,7 @@ const EXAMPLES = {* option takes a value (boolean vs string), surfaces `choices` and `default`.** @param {import('commander').Option} opt- * @returns {{flag: string, description: string, type: string, choices?: string[], default?: unknown, negate?: boolean}}+ * @returns {import('../types/manifest').ManifestOption}*/function describeOption(opt) {const o = /** @type {any} */ (opt);@@ -127,7 +127,7 @@ function describeOption(opt) {/*** Map a Commander positional argument to an arg descriptor.* @param {import('commander').Argument} arg- * @returns {{name: string, required: boolean, variadic: boolean, description: string}}+ * @returns {import('../types/manifest').ManifestArgument}*/function describeArgument(arg) {const a = /** @type {any} */ (arg);@@ -163,7 +163,7 @@ function fullName(cmd, root) {* @param {import('commander').Command} cmd* @param {import('commander').Command} root* @param {Set<string>} jsonSupported fully-qualified names that support --json- * @returns {object | null} null for hidden/internal commands+ * @returns {import('../types/manifest').ManifestCommand | null} null for hidden/internal commands*/function describeCommand(cmd, root, jsonSupported) {const name = fullName(cmd, root);@@ -210,7 +210,7 @@ function describeCommand(cmd, root, jsonSupported) {* command entry doesn't repeat them.** @param {import('commander').Command} program- * @returns {Array<object>}+ * @returns {import('../types/manifest').ManifestOption[]}*/function describeGlobalOptions(program) {const opts = (program.options || []).map(describeOption);@@ -233,7 +233,7 @@ function describeGlobalOptions(program) {* @param {object} [opts]* @param {Set<string>} [opts.jsonSupported] the JSON_SUPPORTED allowlist* @param {string} [opts.version] CLI version (defaults to program.version())- * @returns {object} the manifest `data` payload (sans envelope)+ * @returns {import('../types/manifest').CLIManifest} the manifest `data` payload (sans envelope)*/export function buildManifest(program, opts = {}) {const jsonSupported = opts.jsonSupported || new Set();diff --git a/packages/cli/src/lib/module-loader.mjs b/packages/cli/src/lib/module-loader.mjsindex 7a72f783de..3bb3f7f1f2 100644--- a/packages/cli/src/lib/module-loader.mjs+++ b/packages/cli/src/lib/module-loader.mjs@@ -21,6 +21,7 @@ import * as fs from 'node:fs';import {createJiti} from 'jiti';import {formatZodError} from './config-schema.mjs';+/** @type {ReturnType<typeof createJiti> | undefined} */let jitiInstance;function getJiti() {if (!jitiInstance) {diff --git a/packages/cli/src/lib/package-scanner.mjs b/packages/cli/src/lib/package-scanner.mjsindex bf9bd299d8..29e89080b8 100644--- a/packages/cli/src/lib/package-scanner.mjs+++ b/packages/cli/src/lib/package-scanner.mjs@@ -6,9 +6,28 @@import * as fs from 'node:fs';import * as path from 'node:path';+/**+ * A discovered documentation package (its package.json declares `astryx.docs`).+ * @typedef {object} ScannedPackage+ * @property {string} name+ * @property {string} [version]+ * @property {string} [description]+ * @property {string} [displayName]+ * @property {string} dir+ * @property {Record<string, any>} astryx+ * @property {string} category+ * @property {string} docsDir+ * @property {string[]} components+ */++/**+ * @param {string} scanDir+ * @returns {ScannedPackage[]}+ */export function scanDirectory(scanDir) {if (!fs.existsSync(scanDir)) return [];const entries = fs.readdirSync(scanDir, {withFileTypes: true});+ /** @type {ScannedPackage[]} */const packages = [];for (const entry of entries) {if (!entry.isDirectory()) continue;@@ -40,7 +59,13 @@ export function scanDirectory(scanDir) {return packages;}+/**+ * @param {string[]} packageDirs+ * @param {ScannedPackage[]} [explicitPackages]+ * @returns {ScannedPackage[]}+ */export function scanAllPackages(packageDirs, explicitPackages = []) {+ /** @type {ScannedPackage[]} */const all = [];const seen = new Set();@@ -62,10 +87,17 @@ export function scanAllPackages(packageDirs, explicitPackages = []) {return all;}+/**+ * @param {string} docsDir+ * @returns {string[]}+ */function discoverDocComponents(docsDir) {if (!fs.existsSync(docsDir)) return [];+ /** @type {string[]} */const components = [];+ /** @param {string} dir */function walk(dir) {+ /** @type {import('node:fs').Dirent[]} */let entries;try {entries = fs.readdirSync(dir, {withFileTypes: true});@@ -84,6 +116,11 @@ function discoverDocComponents(docsDir) {return components.sort();}+/**+ * @param {ScannedPackage[]} packages+ * @param {string} name+ * @returns {{pkg: ScannedPackage, docPath: string, componentName: string} | null}+ */export function findComponentInPackages(packages, name) {const lower = name.toLowerCase();for (const pkg of packages) {@@ -95,9 +132,19 @@ export function findComponentInPackages(packages, name) {return null;}+/**+ * @param {string} docsDir+ * @param {string} name+ * @returns {string | null}+ */function findDocFile(docsDir, name) {const target = name + '.doc.mjs';+ /**+ * @param {string} dir+ * @returns {string | null}+ */function walk(dir) {+ /** @type {import('node:fs').Dirent[]} */let entries;try {entries = fs.readdirSync(dir, {withFileTypes: true});diff --git a/packages/cli/src/lib/project.mjs b/packages/cli/src/lib/project.mjsindex 6b7d2f0532..930fb1c24b 100644--- a/packages/cli/src/lib/project.mjs+++ b/packages/cli/src/lib/project.mjs@@ -57,6 +57,29 @@ import {configContentHash,} from './config-cache.mjs';+/**+ * Extract a human-readable message from an unknown thrown value.+ * Reproduces the historical `err?.message ?? String(err)` behavior in a+ * strict-checkJs-safe way: prefer a non-nullish `.message` (covers Error+ * instances and error-like objects thrown by integration code), else `String()`.+ * @param {unknown} err+ * @returns {string}+ */+function errorMessage(err) {+ const message =+ err && typeof err === 'object' && 'message' in err+ ? /** @type {{message: unknown}} */ (err).message+ : undefined;+ return message == null ? String(err) : String(message);+}++/**+ * An integration issue tagged with the owner package. The base+ * {@link import('../types/integration').AstryxIntegrationIssue} fields plus the+ * `package` that produced it, which Project tracks for routing/dedup.+ * @typedef {import('../types/integration').AstryxIntegrationIssue & {package: string}} ProjectIntegrationIssue+ */+/** Conventional config basenames, in load-precedence order. */export const CONFIG_BASENAMES = ['astryx.config.ts',@@ -117,13 +140,13 @@ export class Project {#config;/** @type {string[]} */#integrations;- /** @type {Array<object>} */+ /** @type {import('./integrations.mjs').LoadedIntegration[]} */#loadedIntegrations;/** @type {import('./config-cache.mjs').ConfigCache} */#cache;/** @type {string} */#hash;- /** @type {import('../types/integration').AstryxIntegrationIssue[]} */+ /** @type {ProjectIntegrationIssue[]} */#issues = [];/*** Package names of integrations whose issues have already been collected@@ -137,9 +160,9 @@ export class Project {* @param {object} init* @param {string} init.cwd* @param {string|null} init.configPath- * @param {object} init.config validated AstryxConfig surface+ * @param {import('../types/config').AstryxConfig} init.config validated AstryxConfig surface* @param {string[]} init.integrations- * @param {Array<object>} init.loadedIntegrations+ * @param {import('./integrations.mjs').LoadedIntegration[]} init.loadedIntegrations* @param {import('./config-cache.mjs').ConfigCache} init.cache* @param {string} init.hash config content hash*/@@ -175,8 +198,11 @@ export class Project {const configPath = findConfigPath(cwd);const hash = configContentHash(configPath);+ /** @type {import('../types/config').AstryxConfig} */let config = {integrations: []};+ /** @type {string[]} */let integrations = [];+ /** @type {import('./integrations.mjs').LoadedIntegration[]} */let loadedIntegrations = [];if (configPath) {@@ -204,7 +230,7 @@ export class Project {/*** The validated config surface (same data loadConfig returned, minus the* resolved `loadedIntegrations` which is exposed separately).- * @returns {{integrations?: string[], issuesUrl?: string, hooks?: object, experimental?: object}}+ * @returns {import('../types/config').AstryxConfig}*/get config() {return this.#config;@@ -215,7 +241,7 @@ export class Project {return this.#integrations;}- /** Resolved loaded integrations (lib/integrations.mjs shape). @returns {Array<object>} */+ /** Resolved loaded integrations (lib/integrations.mjs shape). @returns {import('./integrations.mjs').LoadedIntegration[]} */get loadedIntegrations() {return this.#loadedIntegrations;}@@ -245,7 +271,7 @@ export class Project {*/async #memo(kind, produce) {const key = cacheKey(this.#hash, this.#cwd, kind);- const hit = this.#cache.get(key);+ const hit = /** @type {{value: T} | undefined} */ (this.#cache.get(key));if (hit !== undefined) return hit.value;const value = await produce();this.#cache.set(key, {value});@@ -272,7 +298,10 @@ export class Project {});}- /** Package label for a loaded integration. */+ /** Package label for a loaded integration.+ * @param {import('./integrations.mjs').LoadedIntegration} integration+ * @returns {string}+ */#pkgLabel(integration) {return integration?.name ?? integration?.__spec ?? '(integration)';}@@ -281,7 +310,7 @@ export class Project {* Validate one loaded integration and collect any issues. Marks the* integration visited so issues() won't redo the work. Best-effort: a* validator throwing is itself recorded as an issue, never propagated.- * @param {object} integration+ * @param {import('./integrations.mjs').LoadedIntegration} integration*/async #collectIssues(integration) {const pkg = this.#pkgLabel(integration);@@ -294,7 +323,7 @@ export class Project {this.#pushIssue(pkg, {code: 'integration_error',severity: 'error',- message: err?.message ?? String(err),+ message: errorMessage(err),});}}@@ -311,7 +340,7 @@ export class Project {async components() {return this.#memo('components', async () => {const coreDir = findCoreDir(this.#cwd);- /** @type {Array<object>} */+ /** @type {Array<{name: string, package: string, group: string|null, docPath: string|null, sourcePath: string|null, issuesUrl: string|undefined}>} */const records = [];// Core records (no integrations) — never integration-broken.@@ -343,7 +372,7 @@ export class Project {this.#pushIssue(pkg, {code: 'invalid_component',severity: 'error',- message: err?.message ?? String(err),+ message: errorMessage(err),});}}@@ -362,7 +391,7 @@ export class Project {*/async templates() {return this.#memo('templates', async () => {- /** @type {Array<object>} */+ /** @type {any[]} */const templates = [];// Core + external-package templates (discoverTemplates internally also@@ -371,7 +400,7 @@ export class Project {// path so the skip+warn policy and issue collection apply, then dedupe).try {const core = await discoverTemplates(this.#cwd);- for (const t of core) {+ for (const t of /** @type {any[]} */ (core)) {// Skip integration-owned templates here; they are re-added (and// issue-collected) per integration below to honor skip+warn.if (t.package && t.package !== CORE_PACKAGE) continue;@@ -405,7 +434,7 @@ export class Project {this.#pushIssue(pkg, {code: 'invalid_template',severity: 'error',- message: err?.message ?? String(err),+ message: errorMessage(err),});}}@@ -431,6 +460,7 @@ export class Project {// Discover integration codemods per integration so a single broken// integration is skipped (issue collected) without losing the others.+ /** @type {import('./integrations.mjs').LoadedIntegration[]} */const good = [];for (const integration of this.#loadedIntegrations) {await this.#collectIssues(integration);@@ -449,7 +479,7 @@ export class Project {this.#pushIssue(pkg, {code: 'invalid_codemod',severity: 'error',- message: err?.message ?? String(err),+ message: errorMessage(err),});}}diff --git a/packages/cli/src/lib/resolve-theme.mjs b/packages/cli/src/lib/resolve-theme.mjsindex e79ad8b93b..7c6d6dc2d4 100644--- a/packages/cli/src/lib/resolve-theme.mjs+++ b/packages/cli/src/lib/resolve-theme.mjs@@ -25,6 +25,9 @@ const _require = createRequire(import.meta.url);/*** Try to load a module, returning the default export or the module itself.* Returns null if the module cannot be found.+ * @param {string} specifier+ * @param {string} cwd+ * @returns {unknown}*/function tryLoadModule(specifier, cwd) {// For relative/absolute paths, resolve against cwd@@ -49,6 +52,8 @@ function tryLoadModule(specifier, cwd) {* Extract theme data from a loaded module.* Handles both `module.default` and direct `module` patterns,* as well as named exports like `module.theme` or `module.{name}Theme`.+ * @param {any} mod+ * @returns {any}*/function extractTheme(mod) {if (!mod || typeof mod !== 'object') return null;diff --git a/packages/cli/src/lib/string-utils.mjs b/packages/cli/src/lib/string-utils.mjsindex 15816c4fd5..3f2603b9b5 100644--- a/packages/cli/src/lib/string-utils.mjs+++ b/packages/cli/src/lib/string-utils.mjs@@ -13,6 +13,10 @@ export {levenshteinDistance} from './levenshtein.mjs';/*** Find the closest component names to a given (possibly misspelled) name.* Returns matches sorted by distance, filtered to maxDistance.+ * @param {string} name+ * @param {Record<string, string[]>} components+ * @param {number} [maxDistance]+ * @returns {{name: string, distance: number}[]}*/export function findClosestComponents(name, components, maxDistance = 3) {const allNames = Object.values(components).flat();@@ -45,6 +49,11 @@ export function findClosestComponents(name, components, maxDistance = 3) {* 20 name Levenshtein distance 3** Each result: { name, score, reason }+ *+ * @param {string} needle+ * @param {string} coreDir+ * @param {Record<string, string[]>} components+ * @returns {Promise<{name: string, score: number, reason: string}[]>}*/export async function searchComponents(needle, coreDir, components) {const {pathToFileURL} = await import('node:url');@@ -53,8 +62,14 @@ export async function searchComponents(needle, coreDir, components) {const term = needle.toLowerCase();const allNames = Object.values(components).flat();+ /** @type {Map<string, {name: string, score: number, reason: string}>} */const scored = new Map();+ /**+ * @param {string} name+ * @param {number} score+ * @param {string} reason+ */function addMatch(name, score, reason) {const existing = scored.get(name);if (!existing || score > existing.score) {diff --git a/packages/cli/src/lib/term-log.mjs b/packages/cli/src/lib/term-log.mjsindex a781262970..8ca9f1e2eb 100644--- a/packages/cli/src/lib/term-log.mjs+++ b/packages/cli/src/lib/term-log.mjs@@ -21,6 +21,7 @@import {humanLog} from './json.mjs';+/** @param {unknown} msg */const toStr = (msg) => (msg === undefined || msg === null ? '' : String(msg));/**@@ -29,20 +30,28 @@ const toStr = (msg) => (msg === undefined || msg === null ? '' : String(msg));* every one of these, keeping machine-readable stdout clean.*/export const log = {+ /** @param {unknown} msg */message: (msg) => humanLog(toStr(msg)),+ /** @param {unknown} msg */info: (msg) => humanLog(toStr(msg)),+ /** @param {unknown} msg */step: (msg) => humanLog(toStr(msg)),+ /** @param {unknown} msg */success: (msg) => humanLog(`✓ ${toStr(msg)}`),+ /** @param {unknown} msg */warn: (msg) => humanLog(`⚠ ${toStr(msg)}`),+ /** @param {unknown} msg */error: (msg) => humanLog(`✗ ${toStr(msg)}`),};-/** Banner printed at the start of a multi-step command. */+/** Banner printed at the start of a multi-step command.+ * @param {unknown} title */export function intro(title) {humanLog(`\n${toStr(title)}`);}-/** Footer printed at the end of a multi-step command. */+/** Footer printed at the end of a multi-step command.+ * @param {unknown} message */export function outro(message) {humanLog(`${toStr(message)}\n`);}diff --git a/packages/cli/src/lib/xle/browser.mjs b/packages/cli/src/lib/xle/browser.mjsindex 1f07161ea6..3b4b50fa80 100644--- a/packages/cli/src/lib/xle/browser.mjs+++ b/packages/cli/src/lib/xle/browser.mjs@@ -23,11 +23,21 @@ import {hydrateRegistry} from './registry-core.mjs';export {parse, detectForm, XLEParseError, validate, expand, toCompact, toOutline};export {hydrateRegistry, serializeRegistry, ALIAS_TABLE, resolveComponent, SPACING_STEPS} from './registry-core.mjs';-/** Accept either a hydrated registry (Map fields) or serialized JSON. */+/**+ * Accept either a hydrated registry (Map fields) or serialized JSON.+ * @param {import('./xle-ast').Registry | import('./browser').SerializedRegistry | object} registry+ * @returns {import('./xle-ast').Registry}+ */function asRegistry(registry) {- return registry && registry.components instanceof Map ? registry : hydrateRegistry(registry);+ return registry && /** @type {any} */ (registry).components instanceof Map+ ? /** @type {import('./xle-ast').Registry} */ (registry)+ : hydrateRegistry(/** @type {import('./browser').SerializedRegistry} */ (registry));}+/**+ * @param {import('./xle-ast').RawIssue | {message: string, line?: number, col?: number}} issue+ * @returns {string}+ */function formatIssue(issue) {const where = issue.line != null ? `line ${issue.line}: ` : '';return `${where}${issue.message}`;@@ -38,12 +48,12 @@ function formatIssue(issue) {* twin of `layout check`. Never throws on invalid input; returns the errors.** @param {string} expression- * @param {object} registry - serialized or hydrated+ * @param {import('./xle-ast').Registry | import('./browser').SerializedRegistry | object} registry - serialized or hydrated* @param {object} [opts]- * @param {Array} [opts.blocks] - block list for {hint} resolution (default [])+ * @param {import('./browser').XLEBlock[]} [opts.blocks] - block list for {hint} resolution (default [])* @param {'compact'|'outline'|'auto'} [opts.form]* @param {boolean} [opts.loose]- * @returns {{ok: boolean, valid?: boolean, form?: string, errors: Array, warnings: string[], compact?: string, outline?: string, parseError?: object}}+ * @returns {import('./browser').CheckResult}*/export function checkExpression(expression, registry, opts = {}) {const {blocks = [], form = 'auto', loose = false} = opts;@@ -79,13 +89,13 @@ export function checkExpression(expression, registry, opts = {}) {* Returns either {code, ...} or {errors} (never writes files).** @param {string} expression- * @param {object} registry+ * @param {import('./xle-ast').Registry | import('./browser').SerializedRegistry | object} registry* @param {object} [opts]- * @param {Array} [opts.blocks]+ * @param {import('./browser').XLEBlock[]} [opts.blocks]* @param {'compact'|'outline'|'auto'} [opts.form]* @param {boolean} [opts.loose]* @param {string} [opts.name] - generated component name (PascalCase)- * @param {Map} [opts.blockModules] - prepared block sources/imports for splicing;+ * @param {Map<string, import('./xle-ast').BlockModule>} [opts.blockModules] - prepared block sources/imports for splicing;* omit in the browser (hints stay as TODO markers without sources)*/export function expandExpression(expression, registry, opts = {}) {diff --git a/packages/cli/src/lib/xle/expand.mjs b/packages/cli/src/lib/xle/expand.mjsindex 07ddc72e90..32af0c1971 100644--- a/packages/cli/src/lib/xle/expand.mjs+++ b/packages/cli/src/lib/xle/expand.mjs@@ -21,24 +21,31 @@ import {mergeImports, renderImport, prepareSpliceModule} from './splice.mjs';const INDENT = ' ';+/** @param {string | null | undefined} text */function slugify(text) {return String(text).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');}+/** @param {string} text */function camelCase(text) {const parts = slugify(text).split('-').filter(Boolean);if (parts.length === 0) return 'item';return parts[0] + parts.slice(1).map(p => p[0].toUpperCase() + p.slice(1)).join('');}+/** @param {import('./xle-ast').XLEValue} value */function escapeAttr(value) {return String(value).replace(/\\/g, '\\\\').replace(/"/g, '\\"');}+/**+ * @param {import('./xle-ast').XLEItem} item+ * @returns {import('./xle-ast').XLEItem}+ */function cloneItem(item) {// .bound holds a registry reference (Map props) — rebuild it after the// JSON round-trip of the plain AST fields.- const {bound, ...rest} = item;+ const {bound, ...rest} = /** @type {import('./xle-ast').XLENode} */ (item);const copy = JSON.parse(JSON.stringify(rest, (key, value) => {if (key === 'bound') return undefined;return value;@@ -58,16 +65,25 @@ function cloneItem(item) {/*** Substitute Emmet-style `$` counters in payloads and string props.* `\$` escapes a literal dollar sign (prices etc.).+ * @param {string} text+ * @param {number} index*/function subCounterText(text, index) {return text.replace(/\\\$|\$/g, m => (m === '\\$' ? '$' : String(index)));}-/** Strip `\$` escapes when a node is NOT repeated (single emission). */+/**+ * Strip `\$` escapes when a node is NOT repeated (single emission).+ * @param {string} text+ */function unescapeCounterText(text) {return text.replace(/\\\$/g, '$');}+/**+ * @param {import('./xle-ast').XLEItem} node+ * @param {number} index+ */function substituteCounter(node, index) {if (node.kind === 'group') {for (const child of node.children) substituteCounter(child, index);@@ -86,44 +102,69 @@ function substituteCounter(node, index) {}class Emitter {+ /**+ * @param {import('./xle-ast').Registry} registry+ * @param {{componentName?: string, blockModules?: Map<string, import('./xle-ast').BlockModule>}} [options]+ */constructor(registry, options = {}) {this.registry = registry;// importPath → {named:Set, types:Set, default, namespace, sideEffect}+ /** @type {Map<string, import('./xle-ast').ImportEntry>} */this.imports = new Map();+ /** @type {import('./xle-ast').StateEntry[]} */this.states = [];+ /** @type {Set<string>} */this.usedStateNames = new Set();+ /** @type {string[]} */this.todos = [];+ /** @type {Set<string>} */this.componentsUsed = new Set();this.componentName = options.componentName || 'GeneratedLayout';// canonical block key → prepared module ({mode, componentName, ...})this.blockModules = options.blockModules || new Map();// names of blocks already co-defined in this module (dedup)+ /** @type {Map<string, string>} */this.splicedBlocks = new Map(); // key → componentName+ /** @type {string[]} */this.blockDefs = []; // co-defined block source bodies, in first-use order}+ /**+ * @param {string} source+ * @returns {import('./xle-ast').ImportEntry}+ */importEntry(source) {if (!this.imports.has(source)) {this.imports.set(source, {named: new Set(), types: new Set(), default: null, namespace: null, sideEffect: false});}- return this.imports.get(source);+ return /** @type {import('./xle-ast').ImportEntry} */ (this.imports.get(source));}+ /** @param {import('./xle-ast').RegistryComponent} component */addImport(component) {this.importEntry(component.importPath).named.add(component.exportName);this.componentsUsed.add(component.name);}+ /**+ * @param {string} source+ * @param {string} name+ */addNamedImport(source, name) {this.importEntry(source).named.add(name);}+ /**+ * @param {string} name+ * @returns {import('./xle-ast').RegistryComponent | undefined}+ */requireComponent(name) {const component = this.registry.components.get(name);if (component) this.addImport(component);return component;}+ /** @param {string} base */stateName(base) {let name = camelCase(base);if (!/^[a-z]/.test(name)) name = 'v' + name;@@ -134,6 +175,10 @@ class Emitter {return candidate;}+ /**+ * @param {string} base+ * @param {string} initial+ */addState(base, initial) {const name = this.stateName(base);const setter = 'set' + name[0].toUpperCase() + name.slice(1);@@ -143,12 +188,16 @@ class Emitter {// ── value → JSX prop text ────────────────────────────────────────────+ /**+ * @param {import('./xle-ast').XLEValue} value+ * @returns {string | null}+ */jsxValue(value) {if (value === true) return null; // bare flagif (value === false) return '{false}';if (typeof value === 'number') return `{${value}}`;if (typeof value === 'string') return `"${escapeAttr(value)}"`;- if (value && value.__expr) return `{${value.__expr}}`;+ if (value && typeof value === 'object' && '__expr' in value) return `{${value.__expr}}`;if (Array.isArray(value)) {return `{[${value.map(v => (typeof v === 'string' ? `'${v}'` : String(v))).join(', ')}]}`;}@@ -161,6 +210,10 @@ class Emitter {return `{${String(value)}}`;}+ /**+ * @param {string} key+ * @param {import('./xle-ast').XLEValue} value+ */propText(key, value) {const v = this.jsxValue(value);return v === null ? key : `${key}=${v}`;@@ -168,10 +221,14 @@ class Emitter {// ── scaffolding ──────────────────────────────────────────────────────+ /**+ * @param {import('./xle-ast').RegistryProp} prop+ * @param {import('./xle-ast').XLENode} node+ */initialFor(prop, node) {const type = (prop.type || '').trim();- if (node.bound.component.name === 'TabList') {- const tabs = node.children.filter(c => c.kind === 'node');+ if (node.bound?.component.name === 'TabList') {+ const tabs = /** @type {import('./xle-ast').XLENode[]} */ (node.children.filter(c => c.kind === 'node'));const chosen = tabs.find(t => t.selected) || tabs[0];return chosen ? `'${slugify(chosen.payload || chosen.name)}'` : `''`;}@@ -185,6 +242,11 @@ class Emitter {return 'undefined';}+ /**+ * @param {import('./xle-ast').XLENode} node+ * @param {import('./xle-ast').RegistryComponent} component+ * @param {Map<string, import('./xle-ast').XLEValue>} props+ */scaffoldState(node, component, props) {for (const valueKey of ['value', 'page']) {const valueProp = component.props.get(valueKey);@@ -199,6 +261,12 @@ class Emitter {}}+ /**+ * @param {import('./xle-ast').XLENode} node+ * @param {import('./xle-ast').RegistryComponent} component+ * @param {Map<string, import('./xle-ast').XLEValue>} props+ * @param {Set<string>} slotKeys+ */fillRequired(node, component, props, slotKeys) {for (const prop of component.props.values()) {if (!prop.required || props.has(prop.name) || slotKeys.has(prop.name)) continue;@@ -221,7 +289,14 @@ class Emitter {// ── node emission ────────────────────────────────────────────────────+ /**+ * @param {import('./xle-ast').XLEItem[]} items+ * @param {number} depth+ * @param {import('./xle-ast').EmitContext} [context]+ * @returns {string[]}+ */emitItems(items, depth, context = {}) {+ /** @type {string[]} */const lines = [];for (const item of items) {if (item.kind === 'group') {@@ -237,7 +312,7 @@ class Emitter {}const count = item.repeat || 1;for (let i = 1; i <= count; i++) {- const clone = count > 1 ? cloneItem(item) : item;+ const clone = count > 1 ? /** @type {import('./xle-ast').XLENode} */ (cloneItem(item)) : item;if (count > 1) {clone.repeat = null;substituteCounter(clone, i);@@ -248,6 +323,12 @@ class Emitter {return lines;}+ /**+ * @param {import('./xle-ast').XLENode} node+ * @param {number} depth+ * @param {import('./xle-ast').EmitContext} [context]+ * @returns {string[]}+ */emitNode(node, depth, context = {}) {if (!node.bound) {// Anonymous block reference — emit just the block, no wrapper element.@@ -259,6 +340,7 @@ class Emitter {const pad = INDENT.repeat(depth);const props = new Map(node.bound.props);+ /** @type {string | null} */let textChild = null;// Payload → primary text prop, else text child. Required props win@@ -273,7 +355,7 @@ class Emitter {if (target && !props.has(target)) props.set(target, node.payload);else textChild = node.payload;}- if (node.payload2 != null && component.props.has('value') && !component.props.get('value').required) {+ if (node.payload2 != null && component.props.has('value') && !component.props.get('value')?.required) {props.set('value', node.payload2);}@@ -292,9 +374,11 @@ class Emitter {props.delete('__opens');props.delete('__fill');if (opens) {- const target = opens.idref || opens;+ const opensRef = /** @type {import('./xle-ast').IdRef} */ (opens);+ const target = opensRef.idref || opens;const handler = component.props.has('onClick') ? 'onClick' : 'clickAction';- props.set(handler, {__expr: `() => {/* TODO(xle): open #${target.idref ?? target} */}`});+ const targetId = typeof target === 'object' && target != null && 'idref' in target ? target.idref : target;+ props.set(handler, {__expr: `() => {/* TODO(xle): open #${targetId} */}`});}// Slots → element-valued props (keys collected first so required-prop@@ -302,12 +386,14 @@ class Emitter {const slotKeys = new Set(node.bound.slots.map(s => s.key));this.fillRequired(node, component, props, slotKeys);+ /** @type {Array<[string, string[]]>} */const slotEntries = [];for (const slot of node.bound.slots) {slotEntries.push([slot.key, this.emitSlotValue(slot, depth + 1)]);}// Structural routing.+ /** @type {import('./xle-ast').XLEItem[]} */let children = node.children;if (component.name === 'Layout') {const routed = this.routeLayoutChildren(node, props, slotEntries, depth);@@ -356,12 +442,21 @@ class Emitter {return lines;}+ /**+ * @param {import('./xle-ast').RegistryComponent} component+ * @param {Map<string, import('./xle-ast').XLEValue>} props+ * @param {Array<[string, string[]]>} slotEntries+ * @param {string[]} bodyLines+ * @param {number} depth+ * @returns {string[]}+ */renderTag(component, props, slotEntries, bodyLines, depth) {const pad = INDENT.repeat(depth);const propTexts = [...props.entries()].map(([k, v]) => this.propText(k, v));const slotTexts = slotEntries.map(([key, valueLines]) => ({key, valueLines}));const tag = component.exportName;+ /** @type {string[]} */const open = [];const simple = slotTexts.length === 0 && propTexts.join(' ').length <= 60;if (simple) {@@ -385,6 +480,11 @@ class Emitter {return [...open, ...bodyLines, `${pad}</${tag}>`];}+ /**+ * @param {import('./xle-ast').Slot} slot+ * @param {number} _depth+ * @returns {string[]}+ */emitSlotValue(slot, _depth) {const value = slot.value;if (value == null) {@@ -394,17 +494,17 @@ class Emitter {const text = this.requireComponent('Text');return [text ? `<${text.exportName}>${value}</${text.exportName}>` : `<>${value}</>`];}- if (value.hint) {+ if ('hint' in value) {return ['<>',...this.emitHint(value.hint, 1).map(l => l.trimStart()).map(l => INDENT + l),'</>',];}- if (value.idref) {+ if ('idref' in value) {return [`null /* TODO(xle): reference #${value.idref} */`];}- if (value.subexpr) {+ if ('subexpr' in value) {const lines = this.emitItems(value.subexpr, 0, {});if (value.subexpr.length > 1) return ['<>', ...lines.map(l => INDENT + l), '</>'];return lines;@@ -412,6 +512,11 @@ class Emitter {return ['null'];}+ /**+ * @param {import('./xle-ast').Hint} hint+ * @param {number} depth+ * @returns {string[]}+ */emitHint(hint, depth) {const pad = INDENT.repeat(depth);if (hint.block) {@@ -436,6 +541,9 @@ class Emitter {/*** Register a referenced block (import-mode app component, or splice-mode* template block co-defined once) and return the JSX component name to use.+ * @param {string} key+ * @param {import('./xle-ast').BlockModule} mod+ * @returns {string | null | undefined}*/referenceBlock(key, mod) {if (this.splicedBlocks.has(key)) return this.splicedBlocks.get(key);@@ -468,18 +576,27 @@ class Emitter {return name;}+ /**+ * @param {import('./xle-ast').XLENode} node+ * @param {Map<string, import('./xle-ast').XLEValue>} props+ * @param {Array<[string, string[]]>} slotEntries+ * @param {number} depth+ * @returns {import('./xle-ast').XLEItem[]}+ */routeLayoutChildren(node, props, slotEntries, depth) {+ /** @type {Record<string, string>} */const family = {LayoutHeader: 'header',LayoutContent: 'content',LayoutFooter: 'footer',};const assigned = new Set(slotEntries.map(([k]) => k));+ /** @type {import('./xle-ast').XLEItem[]} */const loose = [];let panelCount = 0;for (const child of node.children) {- const childName = child.bound?.component?.name;- let slotName = family[childName];+ const childName = child.kind === 'node' ? child.bound?.component?.name : undefined;+ let slotName = childName ? family[childName] : undefined;if (childName === 'LayoutPanel') {slotName = panelCount === 0 ? 'start' : 'end';panelCount++;@@ -493,7 +610,7 @@ class Emitter {}// Loose children auto-wrap into an implicit LayoutContent slot.if (loose.length > 0 && !assigned.has('content')) {- const lc = this.requireComponent('LayoutContent');+ const lc = /** @type {import('./xle-ast').RegistryComponent} */ (this.requireComponent('LayoutContent'));const inner = this.emitItems(loose, 1, {});slotEntries.push(['content', [`<${lc.exportName}>`, ...inner, `</${lc.exportName}>`]]);} else if (loose.length > 0) {@@ -503,8 +620,13 @@ class Emitter {return [];}- /** Expand groups/repeats into a flat node list (clones carry repeat=null). */+ /**+ * Expand groups/repeats into a flat node list (clones carry repeat=null).+ * @param {import('./xle-ast').XLEItem[]} items+ * @returns {import('./xle-ast').XLENode[]}+ */flattenItems(items) {+ /** @type {import('./xle-ast').XLENode[]} */const out = [];for (const item of items) {const count = item.repeat || 1;@@ -521,26 +643,37 @@ class Emitter {return out;}+ /**+ * @param {import('./xle-ast').XLENode} node+ * @returns {import('./xle-ast').XLEItem[]}+ */partitionTableChildren(node) {const flat = this.flattenItems(node.children);const rows = flat.filter(c => c.kind === 'node' && c.bound?.component?.name === 'TableRow');if (rows.length === 0 || rows.length !== flat.length) return node.children;- const isHeaderRow = (row) => {+ const isHeaderRow = (/** @type {import('./xle-ast').XLENode} */ row) => {const cells = this.flattenItems(row.children);return cells.length > 0 && cells.every(c => c.bound?.component?.name === 'TableHeaderCell');};const headerRows = rows.filter(isHeaderRow);const bodyRows = rows.filter(r => !isHeaderRow(r));+ /**+ * @param {string} name+ * @param {import('./xle-ast').XLENode[]} rowNodes+ * @returns {import('./xle-ast').XLENode}+ */const wrap = (name, rowNodes) => {const comp = this.requireComponent(name);+ /** @type {import('./xle-ast').XLENode} */const wrapper = {kind: 'node', name, id: null, enumMods: [], payload: null, payload2: null,attrs: [], slots: [], hint: null, repeat: null, selected: false,children: rowNodes, line: node.line, col: node.col,- bound: {component: comp, props: new Map(), slots: [], stray: []},+ bound: {component: /** @type {import('./xle-ast').RegistryComponent} */ (comp), props: new Map(), slots: [], stray: []},};return wrapper;};+ /** @type {import('./xle-ast').XLEItem[]} */const out = [];if (headerRows.length > 0) out.push(wrap('TableHeader', headerRows));if (bodyRows.length > 0) out.push(wrap('TableBody', bodyRows));@@ -551,9 +684,9 @@ class Emitter {/*** Expand a validated document into a complete TSX module.*- * @param {{roots: any[], overlays: any[]}} doc- * @param {object} registry- * @param {{componentName?: string}} [options]+ * @param {{roots: import('./xle-ast').XLEItem[], overlays: import('./xle-ast').XLEItem[]}} doc+ * @param {import('./xle-ast').Registry} registry+ * @param {{componentName?: string, blockModules?: Map<string, import('./xle-ast').BlockModule>}} [options]* @returns {{code: string, componentsUsed: string[], states: number, todos: string[]}}*/export function expand(doc, registry, options = {}) {diff --git a/packages/cli/src/lib/xle/parse.mjs b/packages/cli/src/lib/xle/parse.mjsindex 78c15333c3..495aaecf68 100644--- a/packages/cli/src/lib/xle/parse.mjs+++ b/packages/cli/src/lib/xle/parse.mjs@@ -17,6 +17,11 @@*/export class XLEParseError extends Error {+ /**+ * @param {string} message+ * @param {number} line+ * @param {number} col+ */constructor(message, line, col) {super(message);this.name = 'XLEParseError';@@ -25,7 +30,10 @@ export class XLEParseError extends Error {}}-/** Keys that expand to full prop names before validation. */+/**+ * Keys that expand to full prop names before validation.+ * @type {Record<string, string>}+ */export const KEY_ALIASES = {p: 'padding', pad: 'padding', g: 'gap', c: 'columns', cols: 'columns',w: 'width', h: 'height', cp: 'contentPadding', mw: 'maxWidth',@@ -38,6 +46,12 @@ export const KEY_ALIASES = {/** Fused shorthand letters (`p6`, `g4`, `cp2`…) — letter must be a KEY_ALIAS. */const FUSED = new Set(['p', 'g', 'c', 'w', 'h', 'cp', 'mw', 'mh', 'rg', 'cg']);+/**+ * @param {string|null} name+ * @param {number} line+ * @param {number} col+ * @returns {import('./xle-ast').XLENode}+ */export function makeNode(name, line, col) {return {kind: 'node',@@ -57,20 +71,30 @@ export function makeNode(name, line, col) {};}+/**+ * @param {number} line+ * @param {number} col+ * @returns {import('./xle-ast').XLEGroup}+ */function makeGroup(line, col) {return {kind: 'group', repeat: null, children: [], line, col};}// ─── shared low-level helpers ──────────────────────────────────────────────-const isIdentStart = (ch) => /[A-Za-z]/.test(ch);-const isIdent = (ch) => /[A-Za-z0-9_-]/.test(ch);+const isIdentStart = (/** @type {string} */ ch) => /[A-Za-z]/.test(ch);+const isIdent = (/** @type {string} */ ch) => /[A-Za-z0-9_-]/.test(ch);/*** Split a string into tokens at depth-0 whitespace, where (), [], {} and* quotes raise depth. Used for attr blocks and outline lines.+ * @param {string} str+ * @param {number} line+ * @param {number} startCol+ * @returns {Array<{text: string, col: number}>}*/function tokenize(str, line, startCol) {+ /** @type {Array<{text: string, col: number}>} */const tokens = [];let i = 0;while (i < str.length) {@@ -78,6 +102,7 @@ function tokenize(str, line, startCol) {if (i >= str.length) break;const start = i;let depth = 0;+ /** @type {string|null} */let quote = null;while (i < str.length) {const ch = str[i];@@ -101,7 +126,11 @@ function tokenize(str, line, startCol) {return tokens;}-/** Parse a scalar/object/list attr value string into a JS value. */+/**+ * Parse a scalar/object/list attr value string into a JS value.+ * @param {string} raw+ * @returns {import('./xle-ast').XLEValue}+ */export function parseValue(raw) {const s = raw.trim();if (/^(['"]).*\1$/.test(s)) return s.slice(1, -1);@@ -110,6 +139,7 @@ export function parseValue(raw) {if (s === 'false') return false;if (s.startsWith('#')) return {idref: s.slice(1)};if (s.startsWith('{') && s.endsWith('}')) {+ /** @type {Record<string, import('./xle-ast').XLEValue>} */const obj = {};for (const part of splitTop(s.slice(1, -1), ',')) {const idx = part.indexOf(':');@@ -125,10 +155,16 @@ export function parseValue(raw) {return s; // bare ident — enum string}-/** Split on a separator at bracket/quote depth 0. */+/**+ * Split on a separator at bracket/quote depth 0.+ * @param {string} str+ * @param {string} sep+ * @returns {string[]}+ */function splitTop(str, sep) {const parts = [];let depth = 0;+ /** @type {string|null} */let quote = null;let cur = '';for (const ch of str) {@@ -151,7 +187,13 @@ function splitTop(str, sep) {return parts.map(p => p.trim()).filter(Boolean);}-/** Parse `{name +flag +flag2 :arg}` hint body (without braces). */+/**+ * Parse `{name +flag +flag2 :arg}` hint body (without braces).+ * @param {string} body+ * @param {number} line+ * @param {number} col+ * @returns {import('./xle-ast').Hint}+ */function parseHintBody(body, line, col) {const m = body.trim().match(/^([a-z0-9][a-z0-9-]*)((?:\s*\+[a-z0-9-]+)*)(?:\s*:(.*))?$/);if (!m) {@@ -169,8 +211,10 @@ function parseHintBody(body, line, col) {}/**- * Interpret one attribute token. Returns an attr record or mutates node- * for special tokens (slots are returned as {kind:'slot'} records too).+ * Interpret one attribute token. Returns an attr record or a slot record.+ * @param {{text: string, col: number}} token+ * @param {number} line+ * @returns {import('./xle-ast').Attr | import('./xle-ast').Slot}*/function parseAttrToken(token, line) {const {text, col} = token;@@ -182,6 +226,7 @@ function parseAttrToken(token, line) {}const name = text.slice(1, eq);const rest = text.slice(eq + 1);+ /** @type {import('./xle-ast').SlotValue} */let value;if (rest.startsWith('(') && rest.endsWith(')')) {value = {subexpr: parseCompactSiblings(new CompactStream(rest.slice(1, -1), line, col + eq + 2))};@@ -203,6 +248,7 @@ function parseAttrToken(token, line) {// key=value (split at first depth-0 '=')let depth = 0;+ /** @type {string|null} */let quote = null;for (let i = 0; i < text.length; i++) {const ch = text[i];@@ -240,6 +286,11 @@ function parseAttrToken(token, line) {// ─── compact (XLE) surface ─────────────────────────────────────────────────class CompactStream {+ /**+ * @param {string} src+ * @param {number} [line]+ * @param {number} [col]+ */constructor(src, line = 1, col = 1) {this.src = src;this.i = 0;@@ -253,21 +304,29 @@ class CompactStream {const col = (lines.length === 1 ? this.baseCol : 1) + lines[lines.length - 1].length;return {line, col};}+ /** @param {number} [offset] */peek(offset = 0) { return this.src[this.i + offset]; }next() { return this.src[this.i++]; }eof() { return this.i >= this.src.length; }skipWs() { while (!this.eof() && /\s/.test(this.peek())) this.i++; }+ /** @param {string} message */error(message) {const {line, col} = this.pos();throw new XLEParseError(message, line, col);}- /** Consume through the matching close bracket; returns inner text. */+ /**+ * Consume through the matching close bracket; returns inner text.+ * @param {string} open+ * @param {string} close+ * @returns {string}+ */readBalanced(open, close) {const startPos = this.pos();if (this.peek() !== open) this.error(`Expected '${open}'`);this.next();const start = this.i;let depth = 1;+ /** @type {string|null} */let quote = null;while (!this.eof()) {const ch = this.next();@@ -292,6 +351,10 @@ class CompactStream {}}+/**+ * @param {CompactStream} s+ * @returns {import('./xle-ast').XLENode}+ */function parseCompactNode(s) {const {line, col} = s.pos();let name = '';@@ -359,6 +422,10 @@ function parseCompactNode(s) {return node;}+/**+ * @param {CompactStream} s+ * @returns {import('./xle-ast').XLEItem}+ */function parseCompactTerm(s) {s.skipWs();if (s.peek() === '(') {@@ -387,11 +454,20 @@ function parseCompactTerm(s) {return parseCompactNode(s);}+/**+ * @param {import('./xle-ast').XLEItem} node+ * @returns {import('./xle-ast').XLENode}+ */function structuredCloneNode(node) {return JSON.parse(JSON.stringify(node));}+/**+ * @param {CompactStream} s+ * @returns {import('./xle-ast').XLEItem[]}+ */function parseCompactSiblings(s) {+ /** @type {import('./xle-ast').XLEItem[]} */const terms = [];for (;;) {s.skipWs();@@ -410,12 +486,17 @@ function parseCompactSiblings(s) {return terms;}+/**+ * @param {string} source+ * @returns {import('./xle-ast').XLEDoc}+ */export function parseCompact(source) {const parts = source.split(/;;/);const main = new CompactStream(parts[0]);const roots = parseCompactSiblings(main);main.skipWs();if (!main.eof()) main.error(`Unexpected '${main.peek()}'`);+ /** @type {import('./xle-ast').XLEItem[]} */const overlays = [];for (const part of parts.slice(1)) {const s = new CompactStream(part);@@ -428,20 +509,35 @@ export function parseCompact(source) {// ─── outline (XLO) surface ─────────────────────────────────────────────────-/** Parse one outline line's node chain: `Layout > LayoutContent pad=0 !scroll`. */+/**+ * Parse one outline line's node chain: `Layout > LayoutContent pad=0 !scroll`.+ * @param {string} text+ * @param {number} line+ * @returns {{head: import('./xle-ast').XLENode, tail: import('./xle-ast').XLENode}}+ */function parseOutlineChain(text, line) {const segments = splitTop(text, '>');+ /** @type {import('./xle-ast').XLENode | null} */let head = null;+ /** @type {import('./xle-ast').XLENode | null} */let tail = null;for (const segment of segments) {const node = parseOutlineNodeSegment(segment, line);if (!head) head = node;- else tail.children.push(node);+ else /** @type {import('./xle-ast').XLENode} */ (tail).children.push(node);tail = node;}- return {head, tail};+ return /** @type {{head: import('./xle-ast').XLENode, tail: import('./xle-ast').XLENode}} */ ({+ head,+ tail,+ });}+/**+ * @param {string} segment+ * @param {number} line+ * @returns {import('./xle-ast').XLENode}+ */function parseOutlineNodeSegment(segment, line) {const tokens = tokenize(segment, line, 0);if (tokens.length === 0) throw new XLEParseError('Empty node', line, 1);@@ -487,10 +583,17 @@ function parseOutlineNodeSegment(segment, line) {return node;}+/**+ * @param {string} source+ * @returns {import('./xle-ast').XLEDoc}+ */export function parseOutline(source) {+ /** @type {import('./xle-ast').XLEItem[]} */const roots = [];+ /** @type {import('./xle-ast').XLEItem[]} */const overlays = [];// Stack frames: {indent, container: array, node|null}+ /** @type {Array<{indent: number, container: import('./xle-ast').XLEItem[], node: import('./xle-ast').XLENode | null}>} */const stack = [{indent: -1, container: roots, node: null}];let inOverlays = false;@@ -499,7 +602,7 @@ export function parseOutline(source) {const raw = lines[li];const lineNo = li + 1;if (raw.trim() === '' || raw.trim().startsWith('#') || raw.trim().startsWith('//')) continue;- const indent = raw.match(/^[ \t]*/)[0].replace(/\t/g, ' ').length;+ const indent = /** @type {RegExpMatchArray} */ (raw.match(/^[ \t]*/))[0].replace(/\t/g, ' ').length;const text = raw.trim();if (text === 'overlays:') {@@ -530,6 +633,7 @@ export function parseOutline(source) {`Slot '${slotMatch[1]}:' has no parent component`, lineNo, indent + 1,);}+ /** @type {import('./xle-ast').Slot & {value: {subexpr: import('./xle-ast').XLEItem[]}}} */const slot = {kind: 'slot', key: slotMatch[1], value: {subexpr: []}, line: lineNo, col: indent + 1};parent.node.slots.push(slot);const inline = slotMatch[2].trim();@@ -557,6 +661,8 @@ export function parseOutline(source) {* Detect which surface the source uses. Multi-line input is outline* unless every line break sits inside an operator chain (trailing* `>`/`+`/`;;` or unclosed brackets), which is multi-line compact.+ * @param {string} source+ * @returns {'compact'|'outline'}*/export function detectForm(source) {const lines = source.split('\n').map(l => l.trim()).filter(l => l !== '' && !l.startsWith('#') && !l.startsWith('//'));diff --git a/packages/cli/src/lib/xle/print.mjs b/packages/cli/src/lib/xle/print.mjsindex 90c08556c0..055dea74d7 100644--- a/packages/cli/src/lib/xle/print.mjs+++ b/packages/cli/src/lib/xle/print.mjs@@ -13,10 +13,14 @@* @position lib/xle — inverse of parse.mjs*/+/**+ * @param {import('./xle-ast').XLEValue} value+ * @returns {string}+ */function valueText(value) {if (typeof value === 'string') return /[\s,'"]/.test(value) ? `'${value}'` : value;if (typeof value === 'number' || typeof value === 'boolean') return String(value);- if (value && value.idref) return `#${value.idref}`;+ if (value && /** @type {any} */ (value).idref) return `#${/** @type {any} */ (value).idref}`;if (Array.isArray(value)) return `[${value.map(valueText).join(',')}]`;if (typeof value === 'object' && value !== null) {return `{${Object.entries(value)@@ -26,6 +30,10 @@ function valueText(value) {return String(value);}+/**+ * @param {import('./xle-ast').Hint} hint+ * @returns {string}+ */function hintText(hint) {let out = hint.name;for (const flag of hint.flags || []) out += ` +${flag}`;@@ -33,6 +41,7 @@ function hintText(hint) {return `{${out}}`;}+/** @param {import('./xle-ast').XLENode} node */function attrTokens(node) {const tokens = [];for (const attr of node.attrs) {@@ -43,17 +52,22 @@ function attrTokens(node) {return tokens;}+/** @param {import('./xle-ast').XLENode} node */function slotTokensCompact(node) {return node.slots.map(slot => {if (slot.value == null) return `@${slot.key}`;if (typeof slot.value === 'string') return `@${slot.key}='${slot.value}'`;- if (slot.value.hint) return `@${slot.key}=${hintText(slot.value.hint)}`;- if (slot.value.idref) return `@${slot.key}=#${slot.value.idref}`;- if (slot.value.subexpr) return `@${slot.key}=(${siblingsCompact(slot.value.subexpr)})`;+ if ('hint' in slot.value) return `@${slot.key}=${hintText(slot.value.hint)}`;+ if (/** @type {any} */ (slot.value).idref) return `@${slot.key}=#${/** @type {any} */ (slot.value).idref}`;+ if ('subexpr' in slot.value) return `@${slot.key}=(${siblingsCompact(slot.value.subexpr)})`;return `@${slot.key}`;});}+/**+ * @param {import('./xle-ast').XLENode} node+ * @returns {string}+ */function nodeCompact(node) {let out = node.name || '';if (node.id) out += `#${node.id}`;@@ -72,6 +86,10 @@ function nodeCompact(node) {return out;}+/**+ * @param {import('./xle-ast').XLEItem} item+ * @returns {string}+ */function termCompact(item) {if (item.kind === 'group') {let out = `(${siblingsCompact(item.children)})`;@@ -82,6 +100,10 @@ function termCompact(item) {return nodeCompact(item);}+/**+ * @param {import('./xle-ast').XLEItem[]} items+ * @returns {string}+ */function siblingsCompact(items) {return items.map((item, i) => {@@ -96,6 +118,7 @@ function siblingsCompact(items) {.join(' + ');}+/** @param {import('./xle-ast').XLEDoc} doc */export function toCompact(doc) {let out = siblingsCompact(doc.roots);for (const overlay of doc.overlays) {@@ -106,6 +129,11 @@ export function toCompact(doc) {// ── outline ────────────────────────────────────────────────────────────────+/**+ * @param {import('./xle-ast').XLENode} node+ * @param {number} depth+ * @returns {string[]}+ */function nodeOutlineLines(node, depth) {const pad = ' '.repeat(depth);let line = node.name || '';@@ -121,21 +149,23 @@ function nodeOutlineLines(node, depth) {const lines = [pad + line.trimStart()];for (const slot of node.slots) {- if (slot.value && slot.value.subexpr) {- if (slot.value.subexpr.length === 1 && isSimpleNode(slot.value.subexpr[0])) {- const sub = nodeOutlineLines(slot.value.subexpr[0], 0)[0];+ const sv = slot.value;+ if (sv && typeof sv === 'object' && 'subexpr' in sv) {+ const first = sv.subexpr[0];+ if (sv.subexpr.length === 1 && first && isSimpleNode(first)) {+ const sub = nodeOutlineLines(first, 0)[0];lines.push(`${pad} ${slot.key}: ${sub}`);// simple = no children, so the single line is complete} else {lines.push(`${pad} ${slot.key}:`);- for (const sub of slot.value.subexpr) lines.push(...itemOutlineLines(sub, depth + 2));+ for (const sub of sv.subexpr) lines.push(...itemOutlineLines(sub, depth + 2));}- } else if (typeof slot.value === 'string') {- lines.push(`${pad} ${slot.key}: "${slot.value}"`);- } else if (slot.value && slot.value.hint) {- lines.push(`${pad} ${slot.key}: ${hintText(slot.value.hint)}`);- } else if (slot.value && slot.value.idref) {- lines.push(`${pad} ${slot.key}: #${slot.value.idref}`);+ } else if (typeof sv === 'string') {+ lines.push(`${pad} ${slot.key}: "${sv}"`);+ } else if (sv && typeof sv === 'object' && 'hint' in sv) {+ lines.push(`${pad} ${slot.key}: ${hintText(sv.hint)}`);+ } else if (sv && /** @type {any} */ (sv).idref) {+ lines.push(`${pad} ${slot.key}: #${/** @type {any} */ (sv).idref}`);} else {lines.push(`${pad} ${slot.key}:`);}@@ -144,10 +174,19 @@ function nodeOutlineLines(node, depth) {return lines;}+/**+ * @param {import('./xle-ast').XLEItem} item+ * @returns {item is import('./xle-ast').XLENode}+ */function isSimpleNode(item) {return item.kind === 'node' && item.children.length === 0 && item.slots.length === 0;}+/**+ * @param {import('./xle-ast').XLEItem} item+ * @param {number} depth+ * @returns {string[]}+ */function itemOutlineLines(item, depth) {if (item.kind === 'group') {// A repeat-less group exists only to disambiguate compact-form@@ -163,6 +202,7 @@ function itemOutlineLines(item, depth) {return nodeOutlineLines(item, depth);}+/** @param {import('./xle-ast').XLEDoc} doc */export function toOutline(doc) {const lines = [];for (const item of doc.roots) lines.push(...itemOutlineLines(item, 0));diff --git a/packages/cli/src/lib/xle/registry-core.mjs b/packages/cli/src/lib/xle/registry-core.mjsindex c52a0a708a..dd5d699bcf 100644--- a/packages/cli/src/lib/xle/registry-core.mjs+++ b/packages/cli/src/lib/xle/registry-core.mjs@@ -74,6 +74,8 @@ export const SPACING_STEPS = [0, 0.5, 1, 1.5, 2, 3, 4, 5, 6, 8, 10];* Parse enum values from a doc.mjs prop type string.* "'a' | 'b' | 'c'" → ['a','b','c']; "1|2|3" → [1,2,3];* "SpacingStep" → SPACING_STEPS. Mixed/non-enum types → null.+ * @param {string | undefined | null} type+ * @returns {Array<string | number> | null}*/export function parseEnumValues(type) {if (!type || typeof type !== 'string') return null;@@ -83,6 +85,7 @@ export function parseEnumValues(type) {}const parts = t.split('|').map(p => p.trim());if (parts.length < 2) return null;+ /** @type {Array<string | number>} */const values = [];for (const part of parts) {const str = part.match(/^'([^']*)'$/) || part.match(/^"([^"]*)"$/);@@ -93,14 +96,21 @@ export function parseEnumValues(type) {return values;}+/** @param {string} name */export function normalizeName(name) {return name.replace(/^XDS/, '');}/*** Index one doc entry's props into the registry component shape.+ * @param {string} name+ * @param {import('./xle-ast').DocProp[]} props+ * @param {string} dirName+ * @param {string} importPath+ * @returns {import('./xle-ast').RegistryComponent}*/export function toComponentEntry(name, props, dirName, importPath) {+ /** @type {Map<string, import('./xle-ast').RegistryProp>} */const propMap = new Map();for (const p of props || []) {propMap.set(p.name, {@@ -119,10 +129,14 @@ export function toComponentEntry(name, props, dirName, importPath) {/*** Resolve a node name (alias, bare name, or XDS-prefixed name) to a* registry component entry, or null.+ * @param {import('./xle-ast').Registry} registry+ * @param {string | null} name+ * @returns {import('./xle-ast').RegistryComponent | null}*/export function resolveComponent(registry, name) {+ if (name == null) return null;const viaAlias = registry.aliases.get(name);- if (viaAlias) return registry.components.get(viaAlias);+ if (viaAlias) return registry.components.get(viaAlias) ?? null;const bare = normalizeName(name);return registry.components.get(bare) || null;}@@ -130,6 +144,8 @@ export function resolveComponent(registry, name) {/*** Serialize a built registry (with Map fields) to a plain JSON-safe object* so a Node build step can ship it to the browser.+ * @param {import('./xle-ast').Registry} registry+ * @returns {import('./browser').SerializedRegistry}*/export function serializeRegistry(registry) {return {@@ -139,7 +155,7 @@ export function serializeRegistry(registry) {dirName: c.dirName,importPath: c.importPath,undocumented: c.undocumented || false,- props: [...c.props.values()],+ props: /** @type {Array<Record<string, unknown>>} */ (/** @type {unknown} */ ([...c.props.values()])),})),aliases: [...registry.aliases.entries()],componentNames: registry.componentNames,@@ -149,17 +165,26 @@ export function serializeRegistry(registry) {/*** Hydrate a serialized registry back into the Map-bearing shape that* validate()/expand() expect. Inverse of serializeRegistry.+ * @param {import('./browser').SerializedRegistry} json+ * @returns {import('./xle-ast').Registry}*/export function hydrateRegistry(json) {+ /** @type {Map<string, import('./xle-ast').RegistryComponent>} */const components = new Map();for (const c of json.components) {+ /** @type {Map<string, import('./xle-ast').RegistryProp>} */+ const props = new Map();+ for (const p of c.props) {+ const prop = /** @type {import('./xle-ast').RegistryProp} */ (/** @type {unknown} */ (p));+ props.set(String(p.name), prop);+ }components.set(c.name, {name: c.name,exportName: c.exportName,dirName: c.dirName,importPath: c.importPath,undocumented: c.undocumented || false,- props: new Map(c.props.map(p => [p.name, p])),+ props,});}return {diff --git a/packages/cli/src/lib/xle/registry.mjs b/packages/cli/src/lib/xle/registry.mjsindex e1cf626128..1c4df309ef 100644--- a/packages/cli/src/lib/xle/registry.mjs+++ b/packages/cli/src/lib/xle/registry.mjs@@ -40,6 +40,11 @@ export {hydrateRegistry,} from './registry-core.mjs';+/**+ * @param {Record<string, string[]>} grouped+ * @param {string} member+ * @returns {string|null}+ */function findDirFor(grouped, member) {for (const [dir, members] of Object.entries(grouped)) {if (members.includes(member)) return dir;@@ -90,7 +95,7 @@ function readDirExportedComponents(coreDir, dirName) {return [...names];}-let cachedRegistry = null;+let cachedRegistry = /** @type {import('./xle-ast').Registry | null} */ (null);/*** Build (and cache) the registry: every documented component keyed by its@@ -123,7 +128,7 @@ export async function buildRegistry({cwd = process.cwd()} = {}) {}const importPath = resolveImportPath(coreDir, dirName);- const register = (rawName, props) => {+ const register = (/** @type {string} */ rawName, /** @type {import('./xle-ast').DocProp[]} */ props) => {const name = normalizeName(rawName);const entry = toComponentEntry(name, props, dirName, importPath);const existing = components.get(name);@@ -147,7 +152,7 @@ export async function buildRegistry({cwd = process.cwd()} = {}) {// props go missing and valid attrs (e.g. Heading[level=2]) get rejected.// Read every .doc.mjs in each contributing dir and upgrade props, keyed to// each component's own export subpath. Props-only: never adds empty entries.- const upgradeFromDoc = (rawName, props, fallbackDir) => {+ const upgradeFromDoc = (/** @type {string} */ rawName, /** @type {import('./xle-ast').DocProp[]} */ props, /** @type {string} */ fallbackDir) => {if (!props || props.length === 0) return;const name = normalizeName(rawName);// Prefer the component's own export subpath (Heading → @astryxdesign/core/Heading);@@ -193,7 +198,7 @@ export async function buildRegistry({cwd = process.cwd()} = {}) {// (TableHeader/Body/Footer became bare files with no own .doc.mjs after// the un-prefix migration), so we recover them from the real export// surface here.- const registerUndocumented = (name, dirName) => {+ const registerUndocumented = (/** @type {string} */ name, /** @type {string} */ dirName) => {if (components.has(name)) return;const entry = toComponentEntry(name, [], dirName, resolveImportPath(coreDir, name));entry.undocumented = true;diff --git a/packages/cli/src/lib/xle/splice.mjs b/packages/cli/src/lib/xle/splice.mjsindex 64e94fd77f..ae9a99b7c4 100644--- a/packages/cli/src/lib/xle/splice.mjs+++ b/packages/cli/src/lib/xle/splice.mjs@@ -29,9 +29,12 @@ const IMPORT_RE =* default, namespace, and side-effect imports (incl. simple multiline named* lists). Returns {imports, rest} where rest is the source with those import* lines removed.+ * @param {string} source+ * @returns {{imports: import('./xle-ast').ParsedImport[], rest: string}}*/export function parseImportStatements(source) {const lines = source.split('\n');+ /** @type {import('./xle-ast').ParsedImport[]} */const imports = [];const kept = [];for (let i = 0; i < lines.length; i++) {@@ -74,7 +77,7 @@ export function parseImportStatements(source) {** @param {string} source - raw block TSX* @param {string} fallbackName - PascalCase name to use if no export name found- * @returns {{componentName: string, imports: object[], body: string} | null}+ * @returns {import('./xle-ast').PreparedSpliceModule | null}*/export function prepareSpliceModule(source, fallbackName) {const {imports, rest} = parseImportStatements(source);@@ -106,6 +109,8 @@ export function prepareSpliceModule(source, fallbackName) {/*** Merge a parsed import list into an emitter import map.* The map is Map<source, {named:Set, types:Set, default?:string, namespace?:string, sideEffect?:bool}>.+ * @param {Map<string, import('./xle-ast').ImportEntry>} map+ * @param {import('./xle-ast').ParsedImport[]} imports*/export function mergeImports(map, imports) {for (const imp of imports) {@@ -113,6 +118,7 @@ export function mergeImports(map, imports) {map.set(imp.source, {named: new Set(), types: new Set(), default: null, namespace: null, sideEffect: false});}const entry = map.get(imp.source);+ if (!entry) continue;if (imp.sideEffect) entry.sideEffect = true;if (imp.default) entry.default = imp.default;if (imp.namespace) entry.namespace = imp.namespace;@@ -120,7 +126,12 @@ export function mergeImports(map, imports) {}}-/** Render one merged import entry to a statement string. */+/**+ * Render one merged import entry to a statement string.+ * @param {string} source+ * @param {import('./xle-ast').ImportEntry} entry+ * @returns {string}+ */export function renderImport(source, entry) {if (entry.sideEffect && !entry.default && !entry.namespace && entry.named.size === 0 && entry.types.size === 0) {return `import '${source}';`;diff --git a/packages/cli/src/lib/xle/validate.mjs b/packages/cli/src/lib/xle/validate.mjsindex c852ffcb3f..ca97360570 100644--- a/packages/cli/src/lib/xle/validate.mjs+++ b/packages/cli/src/lib/xle/validate.mjs@@ -19,7 +19,10 @@ import {levenshteinDistance} from '../levenshtein.mjs';import {KEY_ALIASES} from './parse.mjs';import {resolveComponent} from './registry-core.mjs';-/** Boolean flag synonyms — agent-frequency spellings of isX/hasX props. */+/**+ * Boolean flag synonyms — agent-frequency spellings of isX/hasX props.+ * @type {Record<string, string>}+ */const FLAG_SYNONYMS = {req: 'isRequired', opt: 'isOptional', dis: 'isDisabled',scroll: 'isScrollable', divider: 'hasDivider', dividers: 'hasDivider',@@ -30,6 +33,12 @@ const FLAG_SYNONYMS = {/** Props the expander treats as the node's primary text payload, in order. */export const PAYLOAD_PROPS = ['label', 'title', 'heading'];+/**+ * @param {string} input+ * @param {string[]} candidates+ * @param {number} [max]+ * @returns {string[]}+ */function suggest(input, candidates, max = 4) {const lower = input.toLowerCase();return candidates@@ -45,6 +54,7 @@ function suggest(input, candidates, max = 4) {.map(s => s.name);}+/** @param {string} name */function normalizeBlockKey(name) {return name.toLowerCase().replace(/[^a-z0-9]/g, '');}@@ -53,6 +63,9 @@ function normalizeBlockKey(name) {* Resolve a word to a prop assignment via, in order: synonym table,* exact boolean prop, is/has-prefixed boolean prop, unique enum value.* Returns {prop, value} or null.+ * @param {import('./xle-ast').RegistryComponent} component+ * @param {string} word+ * @returns {{prop: string, value: string|boolean, ambiguous?: undefined} | {ambiguous: string[], prop?: undefined, value?: undefined} | null}*/function resolveWord(component, word) {const synonym = FLAG_SYNONYMS[word];@@ -67,6 +80,7 @@ function resolveWord(component, word) {if (pref && pref.isBoolean) return {prop: prefix + cap, value: true};}// Unique enum membership across all enum-typed props.+ /** @type {string[]} */const hits = [];for (const prop of component.props.values()) {if (prop.enumValues && prop.enumValues.includes(word)) hits.push(prop.name);@@ -76,7 +90,12 @@ function resolveWord(component, word) {return null;}-/** Map axis-neutral j=/a= keys onto the component's real alignment props. */+/**+ * Map axis-neutral j=/a= keys onto the component's real alignment props.+ * @param {import('./xle-ast').RegistryComponent} component+ * @param {string} key+ * @returns {string}+ */function resolveAxisKey(component, key) {const main = key === '__mainAxis';if (component.name === 'VStack') return main ? 'vAlign' : 'hAlign';@@ -87,9 +106,14 @@ function resolveAxisKey(component, key) {return generic;}-/** Grid's `columns` object shorthand: {min,max,fit|fill} → real keys. */+/**+ * Grid's `columns` object shorthand: {min,max,fit|fill} → real keys.+ * @param {import('./xle-ast').XLEValue} value+ * @returns {import('./xle-ast').XLEValue}+ */function normalizeColumnsObject(value) {if (typeof value !== 'object' || value == null || Array.isArray(value)) return value;+ /** @type {Record<string, import('./xle-ast').XLEValue>} */const out = {};for (const [k, v] of Object.entries(value)) {if (k === 'min') out.minWidth = v;@@ -100,19 +124,35 @@ function normalizeColumnsObject(value) {}export class Validation {+ /**+ * @param {import('./xle-ast').Registry} registry+ * @param {import('./browser').XLEBlock[]} [blocks]+ * @param {{loose?: boolean}} [options]+ */constructor(registry, blocks, {loose = false} = {}) {this.registry = registry;this.blocks = blocks || [];this.blockIndex = new Map(this.blocks.map(b => [normalizeBlockKey(b.dirName), b]));this.loose = loose;+ /** @type {import('./xle-ast').RawIssue[]} */this.errors = [];+ /** @type {import('./xle-ast').RawIssue[]} */this.warnings = [];}+ /**+ * @param {import('./xle-ast').XLENode} node+ * @param {string} message+ * @param {string[]} [suggestions]+ */error(node, message, suggestions = []) {this.errors.push({message, line: node.line, col: node.col, suggestions});}+ /**+ * @param {import('./xle-ast').XLENode} node+ * @param {string} message+ */warn(node, message) {this.warnings.push({message, line: node.line, col: node.col});}@@ -121,6 +161,10 @@ export class Validation {return [...this.registry.aliases.keys(), ...this.registry.componentNames];}+ /**+ * @param {import('./xle-ast').XLENode} node+ * @param {import('./xle-ast').XLENode | null} parent+ */bindNode(node, parent) {// Anonymous block reference ({block} with no host element).if (!node.name && node.hint) {@@ -134,7 +178,7 @@ export class Validation {this.error(node,`Unknown component or alias '${node.name}'`,- suggest(node.name, this.nameCandidates()),+ suggest(node.name ?? '', this.nameCandidates()),);node.bound = null;} else {@@ -148,6 +192,10 @@ export class Validation {for (const child of node.children) this.bindAny(child, node);}+ /**+ * @param {import('./xle-ast').XLEItem} item+ * @param {import('./xle-ast').XLENode | null} parent+ */bindAny(item, parent) {if (item.kind === 'group') {for (const child of item.children) this.bindAny(child, parent);@@ -156,7 +204,12 @@ export class Validation {}}+ /**+ * @param {import('./xle-ast').XLENode} node+ * @param {import('./xle-ast').RegistryComponent} component+ */bindAttrs(node, component) {+ if (!node.bound) return;if (component.undocumented) {// No prop metadata for this export — bind raw and tell the author// nothing was checked, rather than rejecting valid props.@@ -200,7 +253,7 @@ export class Validation {this.error(node,`'!${attr.key}' does not match a boolean prop of ${component.name}`,- suggest(attr.key, [...component.props.keys()].filter(p => component.props.get(p).isBoolean)),+ suggest(attr.key, [...component.props.keys()].filter(p => component.props.get(p)?.isBoolean)),);} else {node.bound.props.set(hit.prop, false);@@ -209,7 +262,13 @@ export class Validation {}}+ /**+ * @param {import('./xle-ast').XLENode} node+ * @param {import('./xle-ast').RegistryComponent} component+ * @param {import('./xle-ast').KvAttr} attr+ */bindKv(node, component, attr) {+ if (!node.bound) return;let key = attr.key.split('.')[0];key = KEY_ALIASES[key] ?? key;@@ -253,7 +312,12 @@ export class Validation {node.bound.props.set(key, value);}+ /**+ * @param {import('./xle-ast').XLENode} node+ * @param {import('./xle-ast').RegistryComponent} component+ */bindMods(node, component) {+ if (!node.bound) return;for (const mod of node.enumMods) {const hit = resolveWord(component, mod);if (!hit || hit.ambiguous) {@@ -273,33 +337,45 @@ export class Validation {}}+ /**+ * @param {import('./xle-ast').XLENode} node+ * @param {import('./xle-ast').RegistryComponent} component+ */bindSlots(node, component) {+ if (!node.bound) return;for (const slot of node.slots) {const prop = component.props.get(slot.key);if (!prop) {this.error(node,`${component.name} has no slot prop '${slot.key}'`,- suggest(slot.key, [...component.props.keys()].filter(k => component.props.get(k).isNode)),+ suggest(slot.key, [...component.props.keys()].filter(k => component.props.get(k)?.isNode)),);continue;}if (!prop.isNode && !prop.isFunction) {this.warn(node, `${component.name}.${slot.key} is typed '${prop.type}' — slot value may not fit`);}- if (slot.value && slot.value.subexpr) {- for (const sub of slot.value.subexpr) this.bindAny(sub, node);+ const sv = slot.value;+ if (sv && typeof sv === 'object' && 'subexpr' in sv) {+ for (const sub of sv.subexpr) this.bindAny(sub, node);}- if (slot.value && slot.value.hint) this.bindHintRef(node, slot.value.hint);+ if (sv && typeof sv === 'object' && 'hint' in sv) this.bindHintRef(node, sv.hint);node.bound.slots.push(slot);}}+ /** @param {import('./xle-ast').XLENode} node */bindHint(node) {this.bindHintRef(node, node.hint);}+ /**+ * @param {import('./xle-ast').XLENode} node+ * @param {import('./xle-ast').Hint | null} hint+ */bindHintRef(node, hint) {+ if (!hint) return;const block = this.blockIndex.get(normalizeBlockKey(hint.name));if (block) {hint.block = {name: block.dirName, description: block.description, category: block.category};@@ -308,7 +384,7 @@ export class Validation {const nearest = suggest(normalizeBlockKey(hint.name),[...this.blockIndex.keys()],- ).map(k => this.blockIndex.get(k).dirName);+ ).map(k => this.blockIndex.get(k)?.dirName).filter(/** @returns {d is string} */ (d) => d != null);if (this.loose) {this.warn(node, `Unknown block '{${hint.name}}' — emitting a TODO placeholder (running with --loose)`);} else {@@ -320,6 +396,11 @@ export class Validation {}}+ /**+ * @param {import('./xle-ast').XLENode} node+ * @param {import('./xle-ast').RegistryComponent} component+ * @param {import('./xle-ast').XLENode | null} parent+ */checkPairings(node, component, parent) {const parentName = parent?.bound?.component?.name ?? parent?.name;if (component.name === 'AppShell' && parent) {@@ -337,11 +418,11 @@ export class Validation {/*** Validate (and bind) a parsed document in place.*- * @param {{roots: any[], overlays: any[]}} doc- * @param {object} registry - from buildRegistry()- * @param {Array<object>} blocks - from template discovery (dirName et al)+ * @param {import('./xle-ast').XLEDoc} doc+ * @param {import('./xle-ast').Registry} registry - from buildRegistry()+ * @param {import('./browser').XLEBlock[]} [blocks] - from template discovery (dirName et al)* @param {{loose?: boolean}} [options]- * @returns {{errors: Array, warnings: Array}}+ * @returns {{errors: import('./xle-ast').RawIssue[], warnings: import('./xle-ast').RawIssue[]}}*/export function validate(doc, registry, blocks, options = {}) {const v = new Validation(registry, blocks, options);diff --git a/packages/cli/src/lib/xle/xle-ast.d.ts b/packages/cli/src/lib/xle/xle-ast.d.tsnew file mode 100644index 0000000000..a39553739d--- /dev/null+++ b/packages/cli/src/lib/xle/xle-ast.d.ts@@ -0,0 +1,214 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** Shared XLE/XLO AST + registry type surface for the .mjs pipeline. */++/** A key=value attribute token. */+export interface KvAttr {+ kind: 'kv';+ key: string;+ value: XLEValue;+ raw?: string;+ line: number;+ col: number;+}++/** A bare flag attribute token (e.g. `scroll`). */+export interface FlagAttr {+ kind: 'flag';+ key: string;+ line: number;+ col: number;+}++/** A negated flag attribute token (e.g. `!scroll`). */+export interface NegAttr {+ kind: 'neg';+ key: string;+ line: number;+ col: number;+}++export type Attr = KvAttr | FlagAttr | NegAttr;++/** Parsed `{name +flag :arg}` block hint body. */+export interface Hint {+ name: string;+ flags: string[];+ arg: string | null;+ /** Set by the validator when the hint resolves to a known block. */+ block?: {name: string; description?: string; category?: string};+}++/** An idref value like `#foo`. */+export interface IdRef {+ idref: string;+}++/** A sub-expression value carrying parsed items. */+export interface SubExprValue {+ subexpr: XLEItem[];+}++/** A hint value nested inside a slot. */+export interface HintValue {+ hint: Hint;+}++/** The value of a slot token. */+export type SlotValue = string | IdRef | SubExprValue | HintValue | null;++/** A slot token (`@key=...`). */+export interface Slot {+ kind: 'slot';+ key: string;+ value: SlotValue;+ line: number;+ col: number;+}++/** Any scalar/structured value an attribute or prop can hold. */+export type XLEValue =+ | string+ | number+ | boolean+ | IdRef+ | {subexpr: XLEItem[]}+ | {hint: Hint}+ | {__expr: string}+ | XLEValue[]+ | {[key: string]: XLEValue};++/** A raw prop entry from a component's `.doc.mjs`. */+export interface DocProp {+ name: string;+ type?: string;+ required?: boolean;+}++/** Registry prop metadata. */+export interface RegistryProp {+ name: string;+ type: string;+ required: boolean;+ enumValues: Array<string | number> | null;+ isBoolean: boolean;+ isFunction: boolean;+ isNode: boolean;+}++/** A resolved registry component entry. */+export interface RegistryComponent {+ name: string;+ exportName: string;+ dirName: string;+ importPath: string;+ undocumented?: boolean;+ props: Map<string, RegistryProp>;+}++/** The hydrated registry shape used by validate()/expand(). */+export interface Registry {+ components: Map<string, RegistryComponent>;+ aliases: Map<string, string>;+ componentNames: string[];+}++/** Binding info attached to a node by the validator. */+export interface BoundInfo {+ component: RegistryComponent;+ props: Map<string, XLEValue>;+ slots: Slot[];+ stray: unknown[];+}++/** A parsed element node. */+export interface XLENode {+ kind: 'node';+ name: string | null;+ id: string | null;+ enumMods: string[];+ payload: string | null;+ payload2: string | null;+ attrs: Attr[];+ slots: Slot[];+ hint: Hint | null;+ repeat: number | null;+ selected: boolean;+ children: XLEItem[];+ line: number;+ col: number;+ /** Set by validate(); null when the name could not be resolved. */+ bound?: BoundInfo | null;+}++/** A parenthesized grouping term. */+export interface XLEGroup {+ kind: 'group';+ repeat: number | null;+ children: XLEItem[];+ line: number;+ col: number;+}++/** Any AST item: an element node or a group. */+export type XLEItem = XLENode | XLEGroup;++/** The parsed document. */+export interface XLEDoc {+ roots: XLEItem[];+ overlays: XLEItem[];+ form: 'compact' | 'outline';+}++/** A parsed import statement (from splice.mjs). */+export interface ParsedImport {+ source: string;+ isType: boolean;+ default: string | null;+ namespace: string | null;+ named: string[];+ sideEffect: boolean;+}++/** A merged import map entry (emitter imports). */+export interface ImportEntry {+ named: Set<string>;+ types: Set<string>;+ default: string | null;+ namespace: string | null;+ sideEffect: boolean;+}++/** A prepared block module for splicing. */+export interface PreparedSpliceModule {+ componentName: string;+ imports: ParsedImport[];+ body: string;+}++/** A prepared block module reference (import or splice mode). */+export interface BlockModule {+ mode: 'import' | 'splice';+ componentName: string;+ importPath: string;+ source: string;+}++/** Emitter emission context. */ export interface EmitContext {+ inStack?: boolean;+}++/** A scaffolded useState entry. */+export interface StateEntry {+ name: string;+ setter: string;+ initial: string;+}++/** Internal validation issue (pre-formatting). */+export interface RawIssue {+ message: string;+ line?: number;+ col?: number;+ suggestions?: string[];+}diff --git a/packages/cli/src/types/base.d.ts b/packages/cli/src/types/base.d.tsindex 5728066f18..aeec7d5343 100644--- a/packages/cli/src/types/base.d.ts+++ b/packages/cli/src/types/base.d.ts@@ -43,13 +43,22 @@ import type {HookDetailParamsResponse,} from './hook';import type {SwizzleListResponse, SwizzleCopyResponse} from './swizzle';-import type {ThemeBuildResponse} from './theme';+import type {+ ThemeBuildResponse,+ ThemeListResponse,+ ThemeAddResponse,+} from './theme';import type {UpgradeListResponse,UpgradeRunResponse,UpgradeStatusResponse,} from './upgrade';import type {SearchResponse} from './search';+import type {+ LayoutExpandResponse,+ LayoutCheckResponse,+ LayoutGrammarResponse,+} from './layout';import type {BuildHelpResponse} from './build';import type {ErrorCode} from './error-codes';import type {ManifestResponse} from './manifest';@@ -116,10 +125,15 @@ export type CLIAnyResponse =| SwizzleListResponse| SwizzleCopyResponse| ThemeBuildResponse+ | ThemeListResponse+ | ThemeAddResponse| UpgradeListResponse| UpgradeRunResponse| UpgradeStatusResponse| SearchResponse+ | LayoutExpandResponse+ | LayoutCheckResponse+ | LayoutGrammarResponse| BuildHelpResponse| ManifestResponse| DoctorResponsediff --git a/packages/cli/src/types/codemod.d.ts b/packages/cli/src/types/codemod.d.tsindex 4a9e0ff6f8..0384546cb9 100644--- a/packages/cli/src/types/codemod.d.ts+++ b/packages/cli/src/types/codemod.d.ts@@ -79,3 +79,88 @@ export declare function createCodemod<T extends AstryxCodemodDef>(export declare function createConfigCodemod<T extends AstryxConfigCodemodDef>(def: T,): AstryxConfigCodemod;++// ---------------------------------------------------------------------------+// Internal types (used by the CLI codemod runner infrastructure & transforms).+// These are not part of the public authoring surface but are shared across the+// .mjs files under src/codemods/ so JSDoc annotations stay consistent.+// ---------------------------------------------------------------------------++/**+ * jscodeshift transform signature. jscodeshift ships no type declarations, so+ * the AST surface (`api.jscodeshift`, paths, node attributes) is untyped by+ * design; transforms operate on it dynamically.+ */+export type CodemodTransform = (+ file: AstryxCodemodFile,+ api: CodemodTransformApi,+) => string | null | undefined;++/**+ * The `api` argument as seen INSIDE a transform implementation. Identical to+ * {@link AstryxCodemodApi} except `jscodeshift` is typed as the callable+ * factory (jscodeshift ships no types, so the AST it returns is untyped). Used+ * by the .mjs transforms so `const j = api.jscodeshift; j(file.source)` type-checks.+ */+export interface CodemodTransformApi {+ jscodeshift: JscodeshiftFactory;+ stats: (...args: unknown[]) => void;+ report: (...args: unknown[]) => void;+}++/**+ * A normalized codemod entry as produced by both the core registry runner and+ * integration discovery. See the header of `run-codemod.mjs` for the contract.+ */+export interface CodemodEntry {+ /** Unique id within its package/version (e.g. the transform module name). */+ id: string;+ /** Whether this is a source-file codemod or a config-file codemod. */+ type: 'code' | 'config';+ /** The codemod itself. */+ codemod: {+ title: string;+ description?: string;+ isOptional?: boolean;+ fileExtensions?: string[];+ transform: CodemodTransform;+ };+ /** Owning package name. */+ package: string;+ /** Owning package version. */+ version?: string;+}++/** The result of running a single codemod over one or more files. */+export interface CodemodRunResult {+ filesChanged: number;+ writtenFiles: string[];+ errors: Array<{file: string; codemod: string; error: string}>;+}++/** The console-like log surface used across the codemod runners. */+export interface CliLog {+ step: (...args: unknown[]) => void;+ info: (...args: unknown[]) => void;+ success: (...args: unknown[]) => void;+ warn: (...args: unknown[]) => void;+ error: (...args: unknown[]) => void;+ message?: (...args: unknown[]) => void;+}++/**+ * The jscodeshift factory (the module's default export / `withParser` root).+ * Callable and carries `withParser`; both return an untyped jscodeshift API.+ *+ * `any` is unavoidable here: jscodeshift ships no types and its AST/builder+ * surface is fully dynamic (`j(src)`, `j.JSXElement`, `path.node`, …). `unknown`+ * would break the callable + index access the transforms rely on.+ */+export interface JscodeshiftFactory {+ /* eslint-disable @typescript-eslint/no-explicit-any */+ (...args: any[]): any;+ withParser: (parser: string) => any;+ /** AST node types and builders (j.JSXElement, j.jsxAttribute, ...) are untyped. */+ [key: string]: any;+ /* eslint-enable @typescript-eslint/no-explicit-any */+}diff --git a/packages/cli/src/types/jscodeshift.d.ts b/packages/cli/src/types/jscodeshift.d.tsnew file mode 100644index 0000000000..48b27f51c7--- /dev/null+++ b/packages/cli/src/types/jscodeshift.d.ts@@ -0,0 +1,19 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Ambient declaration for `jscodeshift`, which ships no type declarations.+ * The AST surface is intentionally untyped; codemod transforms operate on it+ * dynamically. This keeps dynamic `import('jscodeshift')` from tripping TS7016+ * under strict checkJs.+ */+declare module 'jscodeshift' {+ interface JscodeshiftFactory {+ /* eslint-disable @typescript-eslint/no-explicit-any */+ (...args: any[]): any;+ withParser: (parser: string) => any;+ [key: string]: any;+ /* eslint-enable @typescript-eslint/no-explicit-any */+ }+ const jscodeshift: JscodeshiftFactory;+ export default jscodeshift;+}diff --git a/packages/cli/src/types/layout.d.ts b/packages/cli/src/types/layout.d.tsnew file mode 100644index 0000000000..003f626e17--- /dev/null+++ b/packages/cli/src/types/layout.d.ts@@ -0,0 +1,74 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Layout command JSON responses.+ *+ * `astryx layout expand|check|grammar` turn compressed XLE/XLO expressions into+ * validated XDS TSX (or echo canonical surfaces / a grammar cheatsheet).+ *+ * Invocation -> type discriminator+ * -----------------------------------------------------------------+ * astryx --json layout expand "<expr>" -> layout.expand+ * astryx --json layout check "<expr>" -> layout.check+ * astryx --json layout grammar -> layout.grammar+ */++/** The input surface an expression was parsed as. */+export type LayoutForm = 'compact' | 'outline' | 'auto';++/** A validation issue with its formatted, human-readable rendering. */+export interface LayoutIssue {+ line?: number;+ col?: number;+ message: string;+ formatted: string;+ suggestions?: string[];+}++/** A block referenced by a layout expression and how it was spliced in. */+export interface LayoutBlockReference {+ name: string;+ mode: string;+}++/** astryx --json layout expand "<expr>" [path] */+export interface LayoutExpandResponse {+ type: 'layout.expand';+ data: {+ form: LayoutForm;+ code: string;+ componentsUsed: string[];+ /** Number of useState hooks the expansion scaffolded. */+ states: number;+ todos: string[];+ blocksReferenced: LayoutBlockReference[];+ warnings: string[];+ written: string | null;+ };+}++/** astryx --json layout check "<expr>" */+export interface LayoutCheckResponse {+ type: 'layout.check';+ data: {+ valid: boolean;+ form: LayoutForm;+ errors: LayoutIssue[];+ warnings: string[];+ compact: string;+ outline: string;+ };+}++/** astryx --json layout grammar */+export interface LayoutGrammarResponse {+ type: 'layout.grammar';+ data: {+ text: string;+ /** Alias table (short name -> canonical component), from the registry. */+ aliases: Record<string, string>;+ };+}++export type LayoutResponse =+ LayoutExpandResponse | LayoutCheckResponse | LayoutGrammarResponse;diff --git a/packages/cli/src/types/theme.d.ts b/packages/cli/src/types/theme.d.tsindex 61b231770d..416d976321 100644--- a/packages/cli/src/types/theme.d.ts+++ b/packages/cli/src/types/theme.d.ts@@ -6,6 +6,8 @@* Invocation -> type discriminator* ------------------------------------------------------------------* xds --json theme build <file> -> theme.build+ * xds --json theme list -> theme.list+ * xds --json theme add <slug> -> theme.add* (file not found / parse error) -> CLIError*/@@ -21,3 +23,31 @@ export interface ThemeBuildResponse {warnings: string[];};}++/** A single theme entry as surfaced by `theme list`. */+export interface ThemeListEntry {+ slug: string;+ displayName: string;+ description: string;+ maintained: boolean;+}++/** xds --json theme list */+export interface ThemeListResponse {+ type: 'theme.list';+ data: ThemeListEntry[];+}++/** xds --json theme add <slug> */+export interface ThemeAddResponse {+ type: 'theme.add';+ data: {+ slug: string;+ displayName: string;+ maintained: boolean;+ outputDir: string;+ entry: string;+ exportName: string;+ files: string[];+ };+}diff --git a/packages/cli/src/types/upgrade.d.ts b/packages/cli/src/types/upgrade.d.tsindex 9c4802d6b3..b1ba9eaf90 100644--- a/packages/cli/src/types/upgrade.d.ts+++ b/packages/cli/src/types/upgrade.d.ts@@ -55,9 +55,16 @@ export interface UpgradeRunResponse {from: string;to: string;codemods: number;- depsUpdated: string[];+ /** Integration packages processed in this upgrade (by name/spec). */+ integrations: string[];agentDocsRefreshed: boolean;agentDocs: AgentDocsSummary;+ /** Total files changed across core + integration codemods (apply mode). */+ filesChanged?: number;+ /** Total transforms that reported a change. */+ transformsApplied?: number;+ /** Per-codemod errors, when any codemod failed. */+ errors?: Array<{file: string; codemod: string; error: string}>;};}diff --git a/packages/cli/src/utils/paths.mjs b/packages/cli/src/utils/paths.mjsindex 88fce72dd1..fa1a510bec 100644--- a/packages/cli/src/utils/paths.mjs+++ b/packages/cli/src/utils/paths.mjs@@ -78,6 +78,7 @@ export function findProjectRoot(startDir = process.cwd()) {* Returns array of { name, category, docsDir, blocksDir }.*/export function discoverExternalPackages(startDir = process.cwd()) {+ /** @type {Array<{name: string, category: string, docsDir: string, blocksDir: string | null}>} */const externals = [];let dir = startDir;@@ -96,6 +97,7 @@ export function discoverExternalPackages(startDir = process.cwd()) {if (!nodeModulesDir) return externals;+ /** @param {string} searchDir */const scanDir = (searchDir) => {if (!fs.existsSync(searchDir)) return;const entries = fs.readdirSync(searchDir, {withFileTypes: true});@@ -141,6 +143,7 @@ export function discoverExternalPackages(startDir = process.cwd()) {/*** List available component directories in packages/core/src.* Returns directory names that contain Astryx*.tsx files.+ * @param {string} coreDir*/export function listComponents(coreDir) {const srcDir = path.join(coreDir, 'src');diff --git a/packages/core/src/docs-types.ts b/packages/core/src/docs-types.tsindex 78e9c55c79..90b9dad692 100644--- a/packages/core/src/docs-types.ts+++ b/packages/core/src/docs-types.ts@@ -731,6 +731,9 @@ export type TokenPreviewType =export interface ReferenceSection {/** Section title, e.g. "Spacing Tokens", "Light/Dark Mode" */title: string;+ /** Navigation category ('guide' | 'foundations'). Mirrors the parent doc's+ * category so sections can be grouped independently in the docsite nav. */+ category?: string;/** Ordered content blocks. Mix prose, code, tables, and lists freely. */content: ContentBlock[];/** Preview type for token tables in this section. When set, the docsite