An open source design system that's fully customizable and agent ready
TypeScript
[CLI] astryx doctor --built checks a built page or its source (#7886)
Joeyad95f610001c
diff --git a/.changeset/doctor-built.md b/.changeset/doctor-built.mdnew file mode 100644index 0000000000..392a974568--- /dev/null+++ b/.changeset/doctor-built.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[feat] `astryx doctor --built <path>` checks a finished build before you deliver it: a project folder, a build output folder, or one built HTML file. `built-astryx-usage` fails when the path holds no import from an Astryx package (any `@astryxdesign/*` package, or an integration the project installs: a declared dependency whose installed copy has an integration manifest), no component imported from one, and no Astryx styles in built CSS or HTML, and names the template-first way to rebuild it. `built-astryx-purity` warns with the source check of `astryx docs is-my-code-good`: raw elements Astryx has a component for, raw SVG and icon-library icons, inline styles, classes, `stylex.create` and imported stylesheets, each with its file and line, or says the source was not inspected when the path holds no source with JSX, such as a bundle. The files under the path and that package.json are only read; nothing in them runs. Without `--built`, `astryx doctor` runs exactly as before.++@josephfarinadiff --git a/packages/cli/api/doctor/_adapter.mjs b/packages/cli/api/doctor/_adapter.mjsindex ab757fe91d..4fe6bc11ea 100644--- a/packages/cli/api/doctor/_adapter.mjs+++ b/packages/cli/api/doctor/_adapter.mjs@@ -26,7 +26,10 @@ import {} from '../../foundation/release/choose.mjs';import {readReleaseFacts} from '../../foundation/release/project.mjs';import {astryxCommandsOnSearchPath} from '../../foundation/env/search-path.mjs';-import {readDeclaredDependencies} from '../../foundation/integrations/autolink.mjs';+import {+ readDeclaredDependencies,+ scanAutolinkCandidates,+} from '../../foundation/integrations/autolink.mjs';import {computerSkillFile,displayHomePath,@@ -437,3 +440,170 @@ export function installCommandFor(cwd) {export function insideProjectElsewhere(cwd) {return installFolder(cwd)?.moved === true;}++/** Folders `doctor --built` never reads: installs and version control. */+const BUILT_SKIPPED_DIRS = new Set(['node_modules', '.git', '.hg', '.sl']);++/** Folders that hold build output: read for stylesheets, never as source. */+const BUILD_OUTPUT_DIRS = new Set(['.next', 'dist', 'build', 'out', '.output']);++/** `doctor --built` reads at most this many files, of at most this size. */+export const BUILT_FILE_LIMIT = 20000;+export const BUILT_FILE_MAX_MB = 5;+const BUILT_FILE_MAX_BYTES = BUILT_FILE_MAX_MB * 1024 * 1024;++/**+ * The absolute path `doctor --built` checks, or null when it does not exist.+ * @param {string} cwd+ * @param {string} target+ * @returns {string | null}+ */+export function resolveBuiltPath(cwd, target) {+ const resolved = path.resolve(cwd, target);+ return fs.existsSync(resolved) ? resolved : null;+}++/**+ * The files under a `doctor --built` path, in a stable order: each with its+ * path relative to the folder (a file's own name when the path is one file),+ * whether it sits in build output, and a reader that returns its text, or+ * null when it cannot be read or is over 5 MB. Installs and version control+ * are skipped; at most BUILT_FILE_LIMIT files are listed.+ * @param {string} target an existing absolute path+ * @returns {{files: {rel: string, built: boolean, read: () => string | null}[], truncated: boolean, missing?: number}}+ */+export function readBuiltPath(target) {+ /** @param {string} file */+ const reader = file => () => {+ try {+ if (fs.statSync(file).size > BUILT_FILE_MAX_BYTES) return null;+ return fs.readFileSync(file, 'utf8');+ } catch {+ return null;+ }+ };+ if (!fs.statSync(target).isDirectory()) {+ const inBuild = path+ .dirname(target)+ .split(path.sep)+ .some(part => BUILD_OUTPUT_DIRS.has(part));+ /** @type {{rel: string, built: boolean, read: () => string | null}[]} */+ const files = [+ {rel: path.basename(target), built: inBuild, read: reader(target)},+ ];+ let missing = 0;+ // A built page carries its styles and scripts in files it links: read+ // the local ones beside it, as built output.+ if (/\.html?$/iu.test(target)) {+ // A link inside an HTML comment is not one the page loads.+ const page = (reader(target)() ?? '').replace(/<!--[\s\S]*?-->/g, ' ');+ const seen = new Set([path.resolve(target)]);+ for (const match of page.matchAll(+ /<(?:link|script)\b[^>]*?\b(?:href|src)\s*=\s*(?:"([^"#?]+)|'([^'#?]+)|([^\s"'#?>]+))/giu,+ )) {+ const href = match[1] ?? match[2] ?? match[3];+ if (/^(?:[a-z][\w+.-]*:|\/\/)/iu.test(href)) continue;+ // A root-relative link names a file from the build root: the page's+ // folder or the nearest folder above it that holds the file.+ let file = path.resolve(path.dirname(target), href.replace(/^\//u, ''));+ if (href.startsWith('/')) {+ for (let dir = path.dirname(target); ; dir = path.dirname(dir)) {+ const candidate = path.join(dir, href);+ if (fs.existsSync(candidate)) {+ file = candidate;+ break;+ }+ if (path.dirname(dir) === dir) break;+ }+ }+ if (seen.has(file)) continue;+ if (!fs.existsSync(file)) {+ // Only a missing stylesheet could have held Astryx styles; a+ // missing favicon or manifest changes nothing.+ if (+ /\.css$/iu.test(href) ||+ /\brel\s*=\s*["']?stylesheet/iu.test(match[0])+ ) {+ missing++;+ }+ continue;+ }+ seen.add(file);+ files.push({+ rel: path+ .relative(path.dirname(target), file)+ .split(path.sep)+ .join('/'),+ built: true,+ read: reader(file),+ });+ }+ }+ return {files, truncated: false, missing};+ }+ /** @type {{rel: string, built: boolean, read: () => string | null}[]} */+ const files = [];+ // A path that is itself build output (`--built dist`) is read as built.+ /** @type {{dir: string, built: boolean}[]} */+ const stack = [+ {dir: target, built: BUILD_OUTPUT_DIRS.has(path.basename(target))},+ ];+ while (stack.length > 0) {+ const {dir, built} = /** @type {{dir: string, built: boolean}} */ (+ stack.pop()+ );+ let entries;+ try {+ entries = fs.readdirSync(dir, {withFileTypes: true});+ } catch {+ continue;+ }+ entries.sort((a, b) => a.name.localeCompare(b.name));+ for (const entry of entries) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ if (BUILT_SKIPPED_DIRS.has(entry.name)) continue;+ stack.push({+ dir: full,+ built: built || BUILD_OUTPUT_DIRS.has(entry.name),+ });+ } else if (entry.isFile()) {+ if (files.length >= BUILT_FILE_LIMIT) return {files, truncated: true};+ files.push({+ rel: path.relative(target, full).split(path.sep).join('/'),+ built,+ read: reader(full),+ });+ }+ }+ }+ return {files, truncated: false};+}++/**+ * The integration packages whose components count as Astryx for a `--built`+ * path, read without running anything: each dependency the nearest+ * package.json above the path declares whose installed copy, resolved the way+ * the CLI autolinks integrations (a workspace root's hoisted copy included),+ * holds an integration manifest. Every `@astryxdesign/*` package counts+ * beside them.+ * @param {string} target the path as given+ * @param {string} cwd+ * @returns {string[]}+ */+export function builtIntegrationPackages(target, cwd) {+ let dir = path.resolve(cwd, target);+ try {+ if (!fs.statSync(dir).isDirectory()) dir = path.dirname(dir);+ } catch {+ dir = path.resolve(cwd);+ }+ for (let at = dir; ; at = path.dirname(at)) {+ if (fs.existsSync(path.join(at, 'package.json'))) {+ return [+ ...new Set(scanAutolinkCandidates(at).map(candidate => candidate.spec)),+ ];+ }+ if (path.dirname(at) === at) return [];+ }+}diff --git a/packages/cli/api/doctor/built-checks.mjs b/packages/cli/api/doctor/built-checks.mjsnew file mode 100644index 0000000000..2f48c83bb1--- /dev/null+++ b/packages/cli/api/doctor/built-checks.mjs@@ -0,0 +1,807 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx doctor --built <path>`: did a finished build actually use+ * Astryx, and how well? Two checks a coding agent runs before it delivers a+ * page.+ *+ * @input A path: a project folder, a build output folder, or one file (a+ * built `.html` page or a source file), and the package names whose+ * components count as Astryx: every `@astryxdesign/*` package and each+ * integration the project loads (its component catalog's providers).+ * @output `built-astryx-usage`: fails when the path holds no import from those+ * packages, no use of a component imported from them, and no Astryx+ * stylesheet in built CSS or HTML. `built-astryx-purity`: warns with the+ * findings of the source check in `astryx docs is-my-code-good` (raw+ * elements Astryx has a component for, raw SVG and icon-library icons,+ * inline styles, classes, StyleX declarations and imported stylesheets),+ * each with its file and line; info, "not inspected", when the path holds+ * no source with JSX (a bundle is build output, not source).+ * @position Pure: the doctor adapter reads the files (readBuiltPath) and the+ * integration package names (builtIntegrationPackages); nothing here runs+ * project code, its configuration, or a browser. Plain `astryx doctor` does not run+ * it.+ */++import {+ BUILT_FILE_LIMIT,+ BUILT_FILE_MAX_MB,+ readBuiltPath,+ resolveBuiltPath,+} from './_adapter.mjs';+import {formatCliCommand} from '../../foundation/env/package-manager.mjs';+import {parse as parseModule} from '@babel/parser';++/** Source files, read for imports and JSX. */+const SOURCE_EXT = new Set(['.tsx', '.jsx', '.ts', '.js', '.mjs', '.cjs']);++/**+ * The lowercased extension of a relative path, with its dot.+ * @param {string} rel+ */+function extensionOf(rel) {+ const name = rel.slice(rel.lastIndexOf('/') + 1);+ const dot = name.lastIndexOf('.');+ return dot > 0 ? name.slice(dot).toLowerCase() : '';+}++/** Files that hold JSX by their extension. */+const JSX_EXT = new Set(['.tsx', '.jsx']);++/** A cheap test before parsing: a tag or fragment opens somewhere. */+const HAS_JSX = /<(?:[A-Za-z]|>)/;++/**+ * Whether a `.js` or `.mjs` source file holds JSX, read from its parse, or+ * null when it does not parse (Flow, decorators and the like the parser+ * cannot read), so the file counts as not inspected.+ * @param {string} text+ * @returns {boolean | null}+ */+function hasJsx(text) {+ if (!HAS_JSX.test(text)) return false;+ /** @type {any} */+ let ast = null;+ for (const plugins of /** @type {any[][]} */ ([+ ['jsx'],+ ['jsx', 'flow', ['decorators', {decoratorsBeforeExport: true}]],+ ])) {+ try {+ ast = parseModule(text, {+ sourceType: 'unambiguous',+ plugins,+ errorRecovery: true,+ });+ break;+ } catch {+ // try the next set of syntax plugins+ }+ }+ if (!ast) return null;+ /** @type {any[]} */+ const stack = [ast.program];+ while (stack.length > 0) {+ const node = stack.pop();+ if (!node || typeof node.type !== 'string') continue;+ if (node.type === 'JSXElement' || node.type === 'JSXFragment') return true;+ for (const key of Object.keys(node)) {+ if (key === 'loc' || key.endsWith('Comments')) continue;+ const value = node[key];+ if (Array.isArray(value)) {+ for (const child of value) stack.push(child);+ } else if (value && typeof value === 'object') stack.push(value);+ }+ }+ return false;+}++/** Built files, read for an Astryx stylesheet. */+const BUILT_EXT = new Set(['.css', '.html', '.htm', '.js', '.mjs']);++/** How many findings a check message names before it counts the rest. */+const SHOWN = 5;++/**+ * Marks of Astryx's stylesheets that survive a production build: the cascade+ * layers Core's and the themes' CSS declare, and Astryx's own custom+ * properties.+ */+const STYLESHEET_MARK =+ /@layer\s+[^{;]*\bastryx-(?:base|theme)\b|--astryx-[\w-]+/;++/**+ * Raw elements the rubric names a component for (`astryx docs+ * is-my-code-good`, "Common component replacements"), with that owner.+ * @type {Readonly<Record<string, string>>}+ */+const RAW_ELEMENTS = Object.freeze({+ div: '`VStack`, `HStack`, `Grid`, `Card`, `Section` or `Center`',+ span: '`Text`',+ p: '`Text`',+ h1: '`Heading`',+ h2: '`Heading`',+ h3: '`Heading`',+ h4: '`Heading`',+ h5: '`Heading`',+ h6: '`Heading`',+ button: '`Button` or `IconButton`',+ a: '`Link`',+ nav: '`LayoutPanel`',+ aside: '`LayoutPanel`',+ header: '`LayoutHeader`',+ main: '`LayoutContent`',+ ul: '`List`',+ ol: '`List`',+ li: '`ListItem`',+ input: 'the matching form control',+ textarea: 'the matching form control',+ select: 'the matching form control',+ table: '`Table`',+ tr: '`Table`',+ td: '`Table`',+ th: '`Table`',+ hr: '`Divider`',+ dialog: '`Dialog`',+ details: '`Collapsible`',+ summary: '`Collapsible`',+});++/** Raw SVG elements the rubric counts as hand-drawn icons. */+const SVG_ELEMENTS = new Set([+ 'svg',+ 'path',+ 'circle',+ 'rect',+ 'line',+ 'polyline',+ 'polygon',+ 'ellipse',+ 'g',+]);++/** Icon libraries whose components the rubric counts when used directly. */+const ICON_PACKAGES = [+ 'lucide-react',+ 'react-icons',+ '@heroicons/react',+ '@tabler/icons-react',+ '@phosphor-icons/react',+ 'react-feather',+ '@mui/icons-material',+ '@fortawesome/react-fontawesome',+ '@radix-ui/react-icons',+];++/**+ * @typedef {object} BuiltFinding+ * @property {string} category the rubric category: `Astryx components`,+ * `Icons` or `Styling`+ * @property {string} file relative to the checked path+ * @property {number} line 1-based+ * @property {string} message+ */++/**+ * @typedef {object} BuiltScan+ * @property {number} sourceFiles+ * @property {number} jsxFiles source files whose JSX was inspected+ * @property {number} builtFiles+ * @property {number} imports imports from Astryx packages+ * @property {number} importFiles files with one+ * @property {number} componentUses JSX uses of names imported from them+ * @property {string[]} packages the Astryx packages imported, sorted+ * @property {string[]} stylesheets built files with an Astryx stylesheet+ * @property {BuiltFinding[]} findings+ * @property {boolean} truncated whether the file limit cut the read short+ * @property {number} unread source files over the size limit, unreadable, or+ * not parsed+ * @property {string[]} unreadFiles those files, relative to the path+ * @property {number} missingLinks local files a built page links that are not+ * there+ */++/**+ * Whether a package specifier names one of the Astryx packages.+ * @param {string} spec+ * @param {readonly string[]} packages+ */+function isAstryxSpecifier(spec, packages) {+ if (spec.startsWith('@astryxdesign/')) return true;+ return packages.some(name => spec === name || spec.startsWith(`${name}/`));+}++/** @param {string} spec */+function isIconSpecifier(spec) {+ return ICON_PACKAGES.some(+ name => spec === name || spec.startsWith(`${name}/`),+ );+}++/**+ * The 1-based line of an offset.+ * @param {string} text+ * @param {number} at+ */+function lineAt(text, at) {+ if (text !== lineCache.text) {+ /** @type {number[]} */+ const starts = [0];+ for (let i = text.indexOf('\n'); i >= 0; i = text.indexOf('\n', i + 1)) {+ starts.push(i + 1);+ }+ lineCache = {text, starts};+ }+ const {starts} = lineCache;+ let low = 0;+ let high = starts.length - 1;+ while (low < high) {+ const mid = (low + high + 1) >> 1;+ if (starts[mid] <= at) low = mid;+ else high = mid - 1;+ }+ return low + 1;+}++/** The line starts of the last file lineAt read, found once per file. */+/** @type {{text: string | null, starts: number[]}} */+let lineCache = {text: null, starts: [0]};++/**+ * Text with comments blanked out, keeping every offset, so a commented-out+ * tag or import is not read. The comments are the ones `@babel/parser`+ * finds, so a `//` or `/*` in a string or in JSX text is not one; a file it+ * cannot parse falls back to a scan that skips string literals.+ * @param {string} text+ */+function withoutComments(text, ext = '', parsed = commentRanges(text, ext)) {+ if (parsed) {+ const out = text.split('');+ for (const [start, end] of parsed) {+ for (let j = start; j < end; j++) if (out[j] !== '\n') out[j] = ' ';+ }+ return out.join('');+ }+ return scanOutComments(text);+}++/**+ * A source file's syntax tree from `@babel/parser` (TypeScript and JSX, then+ * legacy decorators, then Flow), or null when no attempt parses it.+ * @param {string} text+ * @param {string} ext+ * @returns {any}+ */+function parseSource(text, ext) {+ const typescript = /^\.[cm]?tsx?$/.test(ext);+ const jsx = ext === '.tsx' || !typescript;+ const base = [...(typescript ? ['typescript'] : []), ...(jsx ? ['jsx'] : [])];+ for (const plugins of /** @type {any[][]} */ ([+ base,+ [...base, 'decorators-legacy'],+ ...(typescript+ ? []+ : [['jsx', 'flow', ['decorators', {decoratorsBeforeExport: true}]]]),+ ])) {+ try {+ return parseModule(text, {+ sourceType: 'unambiguous',+ plugins,+ errorRecovery: true,+ });+ } catch {+ // try the next set of syntax plugins+ }+ }+ return null;+}++/**+ * The comment ranges `@babel/parser` finds in a source file, or null when it+ * cannot parse the file.+ * @param {string} text+ * @param {string} ext+ * @param {any} [ast]+ * @returns {Array<[number, number]> | null}+ */+function commentRanges(text, ext, ast = parseSource(text, ext)) {+ if (!ast) return null;+ return (ast.comments ?? []).map(+ (/** @type {any} */ c) =>+ /** @type {[number, number]} */ ([c.start, c.end]),+ );+}++/**+ * The imports a parsed source file makes, read from its syntax tree so that+ * an import written in a string, a template literal or JSX text (a code+ * sample on a page) is not one: import and export-from declarations, and+ * `require()` and `import()` of a string.+ * @param {any} ast+ * @returns {{spec: string, names: string[], at: number}[]}+ */+function astImports(ast) {+ /** @type {{spec: string, names: string[], at: number}[]} */+ const found = [];+ for (const node of ast.program.body) {+ if (node.type === 'ImportDeclaration') {+ found.push({+ spec: node.source.value,+ names: node.specifiers.map(+ (/** @type {any} */ each) => each.local.name,+ ),+ at: node.start,+ });+ } else if (+ (node.type === 'ExportNamedDeclaration' ||+ node.type === 'ExportAllDeclaration') &&+ node.source+ ) {+ found.push({spec: node.source.value, names: [], at: node.start});+ }+ }+ /** @type {any[]} */+ const stack = [ast.program];+ while (stack.length > 0) {+ const node = stack.pop();+ if (!node || typeof node.type !== 'string') continue;+ if (+ node.type === 'CallExpression' &&+ (node.callee?.type === 'Import' ||+ (node.callee?.type === 'Identifier' &&+ node.callee.name === 'require')) &&+ node.arguments?.[0]?.type === 'StringLiteral'+ ) {+ found.push({spec: node.arguments[0].value, names: [], at: node.start});+ }+ for (const key of Object.keys(node)) {+ if (key === 'loc' || key.endsWith('Comments')) continue;+ const value = node[key];+ if (Array.isArray(value)) {+ for (const child of value) stack.push(child);+ } else if (value && typeof value === 'object') stack.push(value);+ }+ }+ return found;+}++/**+ * Text with comments blanked by a scan that skips string literals, for a+ * file the parser cannot read.+ * @param {string} text+ */+function scanOutComments(text) {+ const out = text.split('');+ /** @type {string | null} the quote of the string being read */+ let quote = null;+ for (let i = 0; i < text.length; i++) {+ const char = text[i];+ if (quote) {+ if (char === '\\') i++;+ else if (char === quote || (char === '\n' && quote !== '`')) quote = null;+ continue;+ }+ if (char === '"' || char === "'" || char === '`') {+ quote = char;+ continue;+ }+ if (char !== '/') continue;+ const next = text[i + 1];+ if (next !== '/' && next !== '*') continue;+ const end =+ next === '/'+ ? (text.indexOf('\n', i) + 1 || text.length + 1) - 1+ : (text.indexOf('*/', i + 2) + 1 || text.length - 1) + 1;+ for (let j = i; j < end; j++) if (out[j] !== '\n') out[j] = ' ';+ i = end - 1;+ }+ return out.join('');+}++/**+ * The imports of a source file: each specifier with the local names it binds.+ * @param {string} text+ * @returns {{spec: string, names: string[], at: number}[]}+ */+function importsOf(text) {+ /** @type {{spec: string, names: string[], at: number}[]} */+ const found = [];+ const fromImport =+ /\bimport\s+(?:type\s+)?([^'";]*?)\s+from\s+['"]([^'"]+)['"]|\bimport\s+['"]([^'"]+)['"]/g;+ for (const match of text.matchAll(fromImport)) {+ const at = /** @type {number} */ (match.index);+ if (match[3]) {+ found.push({spec: match[3], names: [], at});+ continue;+ }+ const clause = match[1];+ /** @type {string[]} */+ const names = [];+ const braces = /\{([\s\S]*)\}/.exec(clause);+ if (braces) {+ for (const part of braces[1].split(',')) {+ const local = part+ .trim()+ .replace(/^type\s+/, '')+ .split(/\s+as\s+/)+ .pop()+ ?.trim();+ if (local) names.push(local);+ }+ }+ const outside = clause.replace(/\{[\s\S]*\}/, '');+ for (const part of outside.split(',')) {+ const name = part.trim().replace(/^\*\s+as\s+/, '');+ if (/^[A-Za-z_$][\w$]*$/.test(name)) names.push(name);+ }+ found.push({spec: match[2], names, at});+ }+ // A barrel that re-exports a package reaches it as an import does.+ for (const match of text.matchAll(+ /\bexport\s+(?:type\s+)?(?:\*(?:\s+as\s+[\w$]+)?|\{[^}]*\})\s*from\s+['"]([^'"]+)['"]/g,+ )) {+ found.push({+ spec: match[1],+ names: [],+ at: /** @type {number} */ (match.index),+ });+ }+ for (const match of text.matchAll(+ /\brequire\(\s*['"]([^'"]+)['"]\s*\)|\bimport\(\s*['"]([^'"]+)['"]\s*\)/g,+ )) {+ found.push({+ spec: match[1] ?? match[2],+ names: [],+ at: /** @type {number} */ (match.index),+ });+ }+ return found;+}++/**+ * The source findings of one JSX file.+ * @param {string} text comments blanked+ * @param {string} rel+ * @param {Set<string>} iconNames local names imported from icon libraries+ * @returns {BuiltFinding[]}+ */+function jsxFindings(text, rel, iconNames) {+ /** @type {BuiltFinding[]} */+ const findings = [];+ for (const match of text.matchAll(/<([a-z][a-z0-9]*)(?=[\s/>])([^>]*)/g)) {+ const tag = match[1];+ const at = /** @type {number} */ (match.index);+ const line = lineAt(text, at);+ if (SVG_ELEMENTS.has(tag)) {+ // A helper's SVG counts once: by its root element.+ if (tag === 'svg') {+ findings.push({+ category: 'Icons',+ file: rel,+ line,+ message:+ 'raw `<svg>`: render icons through `Icon`, `IconButton` or an icon prop',+ });+ }+ continue;+ }+ const owner = RAW_ELEMENTS[tag];+ if (!owner) continue;+ // Native semantics the rubric keeps: hidden form state.+ if (tag === 'input' && /\btype\s*=\s*["']hidden["']/.test(match[2])) {+ continue;+ }+ findings.push({+ category: 'Astryx components',+ file: rel,+ line,+ message: `raw \`<${tag}>\`: use ${owner}`,+ });+ }+ for (const name of iconNames) {+ for (const match of text.matchAll(+ new RegExp(`<${name.replace(/[$]/g, '\\$')}(?=[\\s/>])`, 'g'),+ )) {+ findings.push({+ category: 'Icons',+ file: rel,+ line: lineAt(text, /** @type {number} */ (match.index)),+ message: `\`<${name}>\` from an icon library: render it through \`Icon\` or an icon prop`,+ });+ }+ }+ for (const [pattern, what] of /** @type {const} */ ([+ [/\bstyle\s*=\s*\{/g, 'an inline `style`'],+ [/\bclassName\s*=/g, 'a `className`'],+ ])) {+ for (const match of text.matchAll(pattern)) {+ findings.push({+ category: 'Styling',+ file: rel,+ line: lineAt(text, /** @type {number} */ (match.index)),+ message: `${what}: use a component prop or token first`,+ });+ }+ }+ return findings;+}++/**+ * Read a path and gather the evidence both checks judge.+ * @param {string} target an existing file or folder+ * @param {readonly string[]} packages package names whose components count as+ * Astryx, beside every `@astryxdesign/*` package+ * @returns {BuiltScan}+ */+export function scanBuilt(target, packages) {+ const {files, truncated, missing = 0} = readBuiltPath(target);+ /** @type {BuiltScan} */+ const scan = {+ sourceFiles: 0,+ jsxFiles: 0,+ builtFiles: 0,+ imports: 0,+ importFiles: 0,+ componentUses: 0,+ packages: [],+ stylesheets: [],+ findings: [],+ truncated,+ unread: 0,+ unreadFiles: [],+ missingLinks: missing,+ };+ const imported = new Set();+ for (const {rel, built, read} of files) {+ const ext = extensionOf(rel);+ // A bundler emits no .tsx or .jsx, so one inside a folder named like+ // build output is still source.+ const isSource =+ SOURCE_EXT.has(ext) &&+ !rel.endsWith('.d.ts') &&+ (!built || JSX_EXT.has(ext));+ const isBuilt = BUILT_EXT.has(ext) && (built || !isSource);+ if (!isSource && !isBuilt) continue;+ const raw = read();+ if (raw == null) {+ if (isSource) {+ scan.unread++;+ scan.unreadFiles.push(rel);+ }+ continue;+ }+ if (isBuilt) {+ scan.builtFiles++;+ // A commented-out rule or import is not Astryx styling.+ const styles =+ ext === '.css' || ext === '.html' || ext === '.htm'+ ? raw.replace(/\/\*[\s\S]*?\*\/|<!--[\s\S]*?-->/g, ' ')+ : raw;+ if (STYLESHEET_MARK.test(styles)) scan.stylesheets.push(rel);+ // A stylesheet that imports an Astryx package's CSS, as the+ // getting-started setup does, uses Astryx.+ if (ext === '.css') {+ for (const match of styles.matchAll(+ /@import\s+(?:url\(\s*)?['"]?([^'")\s;]+)/g,+ )) {+ if (!isAstryxSpecifier(match[1], packages)) continue;+ scan.imports++;+ scan.importFiles++;+ imported.add(+ match[1]+ .split('/')+ .slice(0, match[1].startsWith('@') ? 2 : 1)+ .join('/'),+ );+ }+ }+ }+ if (!isSource) continue;+ scan.sourceFiles++;+ const ast = parseSource(raw, ext);+ const ranges = commentRanges(raw, ext, ast);+ const text = withoutComments(raw, ext, ranges);+ const astryxNames = new Set();+ const iconNames = new Set();+ let fileImports = 0;+ for (const {spec, names, at} of ast ? astImports(ast) : importsOf(text)) {+ if (isAstryxSpecifier(spec, packages)) {+ fileImports++;+ imported.add(+ spec.startsWith('@')+ ? spec.split('/').slice(0, 2).join('/')+ : spec.split('/')[0],+ );+ for (const name of names) astryxNames.add(name);+ } else if (isIconSpecifier(spec)) {+ for (const name of names) iconNames.add(name);+ } else if (/\.(?:css|scss|sass|less)$/.test(spec)) {+ scan.findings.push({+ category: 'Styling',+ file: rel,+ line: lineAt(text, at),+ message: `imports the stylesheet \`${spec}\`: use component props and tokens`,+ });+ }+ }+ for (const match of text.matchAll(/\bstylex\.create\s*\(/g)) {+ scan.findings.push({+ category: 'Styling',+ file: rel,+ line: lineAt(text, /** @type {number} */ (match.index)),+ message:+ 'a `stylex.create` declaration: use a component prop or token first',+ });+ }+ scan.imports += fileImports;+ if (fileImports > 0) scan.importFiles++;+ for (const name of astryxNames) {+ if (!/^[A-Z]/.test(name)) continue;+ const uses = text.match(new RegExp(`<${name}(?=[\\s/>.])`, 'g'));+ scan.componentUses += uses?.length ?? 0;+ }+ // A file the parser cannot read is not inspected: its imports still+ // count, but no finding is read from it.+ if (ranges === null && (JSX_EXT.has(ext) || /\.[cm]?js$/u.test(ext))) {+ scan.unread++;+ scan.unreadFiles.push(rel);+ continue;+ }+ const jsx = /\.[cm]?js$/u.test(ext) ? hasJsx(text) : false;+ if (jsx === null) {+ scan.unread++;+ scan.unreadFiles.push(rel);+ continue;+ }+ if (JSX_EXT.has(ext) || jsx) {+ scan.jsxFiles++;+ for (const finding of jsxFindings(text, rel, iconNames)) {+ scan.findings.push(finding);+ }+ }+ }+ scan.packages = [...imported].sort();+ scan.findings.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);+ return scan;+}++/**+ * @param {number} count+ * @param {string} word+ */+function plural(count, word) {+ return `${count} ${word}${count === 1 ? '' : 's'}`;+}++/**+ * The two checks for a path.+ * @param {string} target as the caller gave it+ * @param {{cwd: string, packages: readonly string[]}} options `packages`: the+ * integration packages whose components count as Astryx+ * @returns {import('./doctor.type.mjs').DoctorCheck[]}+ */+export function checkBuilt(target, {cwd, packages}) {+ const resolved = resolveBuiltPath(cwd, target);+ if (resolved == null) {+ return [+ {+ id: 'built-astryx-usage',+ label: 'Built output uses Astryx',+ status: 'fail',+ message: `${target} does not exist, so nothing was checked.`,+ fix: 'Pass the project folder, the build output folder, or the built HTML file.',+ },+ ];+ }+ const scan = scanBuilt(resolved, packages);+ const used =+ scan.imports > 0 || scan.componentUses > 0 || scan.stylesheets.length > 0;+ const read = `${plural(scan.sourceFiles, 'source file')} and ${plural(scan.builtFiles, 'built file')}${scan.truncated ? ` (the first ${BUILT_FILE_LIMIT} files)` : ''}`;+ const evidence = [+ scan.imports > 0+ ? `${plural(scan.imports, 'import')} from ${scan.packages.join(', ')} in ${plural(scan.importFiles, 'file')}`+ : null,+ scan.componentUses > 0+ ? `${plural(scan.componentUses, 'component use')}`+ : null,+ scan.stylesheets.length > 0+ ? `Astryx styles in ${scan.stylesheets.slice(0, 3).join(', ')}${scan.stylesheets.length > 3 ? ` and ${scan.stylesheets.length - 3} more` : ''}`+ : null,+ ].filter(Boolean);+ /** @type {import('./doctor.type.mjs').DoctorCheck} */+ const usage = used+ ? {+ id: 'built-astryx-usage',+ label: 'Built output uses Astryx',+ status: 'pass',+ message: `Read ${read}: ${evidence.join('; ')}.`,+ }+ : scan.sourceFiles === 0 &&+ scan.builtFiles === 0 &&+ scan.unread === 0 &&+ !scan.truncated+ ? {+ id: 'built-astryx-usage',+ label: 'Built output uses Astryx',+ status: 'fail',+ message: `${target} holds no source or built files, so nothing was checked.`,+ fix: 'Pass the project folder, the build output folder, or the built HTML file.',+ }+ : scan.truncated || scan.unread > 0 || scan.missingLinks > 0+ ? {+ id: 'built-astryx-usage',+ label: 'Built output uses Astryx',+ status: 'warn',+ message: `Read ${read} and found no Astryx in them, but ${[scan.truncated ? `the rest past the first ${BUILT_FILE_LIMIT} files` : null, scan.unread > 0 ? `${plural(scan.unread, 'source file')} over ${BUILT_FILE_MAX_MB} MB, unreadable or unparsed` : null, scan.missingLinks > 0 ? `${plural(scan.missingLinks, 'file')} the page links but that are not there` : null].filter(Boolean).join(' and ')} went unread, so this does not show whether the output uses Astryx.`,+ fix: `Run \`${formatCliCommand('doctor --built <folder>', cwd)}\` on the folder that holds the page itself, or on its build output.`,+ }+ : {+ id: 'built-astryx-usage',+ label: 'Built output uses Astryx',+ status: 'fail',+ message: `Read ${read}: no import from an Astryx package, no Astryx component, and no Astryx styles, so this output does not use Astryx.`,+ fix: `Rebuild the page from an Astryx template: run \`${formatCliCommand('build "<what the page is>"', cwd)}\`, scaffold the template it names, and fill it with Astryx components. Do not deliver this output.`,+ };+ const unreadNames =+ scan.unreadFiles.slice(0, SHOWN).join(', ') ++ (scan.unreadFiles.length > SHOWN+ ? ` and ${scan.unreadFiles.length - SHOWN} more`+ : '');+ const unreadNote =+ scan.unread > 0+ ? ` ${plural(scan.unread, 'source file')} went unread (over ${BUILT_FILE_MAX_MB} MB, unreadable or not parsed), so ${scan.unread === 1 ? 'it was' : 'they were'} not inspected: ${unreadNames}.`+ : '';+ /** @type {import('./doctor.type.mjs').DoctorCheck} */+ let purity;+ if (scan.jsxFiles === 0) {+ purity = {+ id: 'built-astryx-purity',+ label: 'Source uses Astryx well',+ status: 'info',+ message: `Not inspected: ${plural(scan.sourceFiles, 'source file')} under ${target} and no JSX read among them, so components, icons and styles were not checked. A bundle or other build output is not source.${unreadNote}`,+ fix: `Run \`${formatCliCommand('doctor --built <project folder>', cwd)}\` on the folder that holds the page's source.`,+ };+ } else if (+ scan.findings.length === 0 &&+ (scan.truncated || scan.unread > 0)+ ) {+ purity = {+ id: 'built-astryx-purity',+ label: 'Source uses Astryx well',+ status: 'info',+ message: `Not fully inspected: ${plural(scan.jsxFiles, 'source file')} with JSX had no finding${scan.truncated ? `, but only the first ${BUILT_FILE_LIMIT} files were read` : ''}.${unreadNote}`,+ fix: `Run \`${formatCliCommand('doctor --built <folder>', cwd)}\` on the folder that holds the page's own source.`,+ };+ } else if (scan.findings.length === 0) {+ purity = {+ id: 'built-astryx-purity',+ label: 'Source uses Astryx well',+ status: 'pass',+ message: `${plural(scan.jsxFiles, 'source file')} with JSX: no raw element Astryx has a component for, no hand-drawn or library icon, and no custom styling.`,+ };+ } else {+ /** @type {Record<string, number>} */+ const byCategory = {};+ for (const finding of scan.findings) {+ byCategory[finding.category] = (byCategory[finding.category] ?? 0) + 1;+ }+ const counts = Object.entries(byCategory)+ .map(([category, count]) => `${category} ${count}`)+ .join(', ');+ const shown = scan.findings+ .slice(0, SHOWN)+ .map(finding => `${finding.file}:${finding.line} ${finding.message}`)+ .join('; ');+ const more =+ scan.findings.length > SHOWN+ ? `; and ${scan.findings.length - SHOWN} more`+ : '';+ purity = {+ id: 'built-astryx-purity',+ label: 'Source uses Astryx well',+ status: 'warn',+ message: `${plural(scan.findings.length, 'finding')} (${counts}): ${shown}${more}.${unreadNote}${scan.truncated ? ` Only the first ${BUILT_FILE_LIMIT} files were read.` : ''}`,+ fix: `Replace each with the Astryx component, icon surface, prop or token it names; \`${formatCliCommand('docs is-my-code-good', cwd)}\` has the full rubric. Keep a raw element only where its native meaning is needed.`,+ };+ }+ return [usage, purity];+}diff --git a/packages/cli/api/doctor/built-checks.test.mjs b/packages/cli/api/doctor/built-checks.test.mjsnew file mode 100644index 0000000000..491275048b--- /dev/null+++ b/packages/cli/api/doctor/built-checks.test.mjs@@ -0,0 +1,502 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {performance} from 'node:perf_hooks';+import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import {checkBuilt, scanBuilt} from './built-checks.mjs';+import {builtIntegrationPackages} from './_adapter.mjs';+import {runChecks} from './doctor.mjs';+import {runCli} from '../../test-utils/run-cli.mjs';++/** @type {string} */+let dir;++/**+ * @param {Record<string, string>} files relative path → contents+ */+function write(files) {+ for (const [rel, text] of Object.entries(files)) {+ const file = path.join(dir, rel);+ fs.mkdirSync(path.dirname(file), {recursive: true});+ fs.writeFileSync(file, text);+ }+}++/** @param {string} target @param {string[]} [packages] */+function check(target, packages = []) {+ const [usage, purity] = checkBuilt(target, {cwd: dir, packages});+ return {usage, purity};+}++beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-built-'));+});++afterEach(() => {+ fs.rmSync(dir, {recursive: true, force: true});+});++describe('built-astryx-usage', () => {+ it('fails a hand-written page with no Astryx at all, with the way to rebuild it', () => {+ write({+ 'out/index.html':+ '<!doctype html><html><head><style>.cat{display:flex}</style></head><body><div class="cat"><h1>Cats</h1></div></body></html>',+ });++ for (const target of ['out', 'out/index.html']) {+ const {usage, purity} = check(target);+ expect(usage.status).toBe('fail');+ expect(usage.message).toContain('does not use Astryx');+ expect(usage.fix).toContain('build "<what the page is>"');+ expect(usage.fix).toContain('Do not deliver');+ // Built HTML is not source: the purity check says it did not run.+ expect(purity.status).toBe('info');+ }+ });++ it('passes source that imports Astryx components and uses them', () => {+ write({+ 'src/Page.tsx':+ 'import {Button} from \'@astryxdesign/core/Button\';\nexport const Page = () => <Button label="Go" />;\n',+ });++ const {usage} = check('.');+ expect(usage.status).toBe('pass');+ expect(usage.message).toContain('1 import from @astryxdesign/core');+ expect(usage.message).toContain('1 component use');+ });++ it("counts an integration's components as Astryx, by the package names the project loads", () => {+ write({+ 'app/page.tsx':+ 'import {AcmeBadge} from \'@acme/ui/Badge\';\nexport default () => <AcmeBadge label="New" />;\n',+ });++ expect(check('.').usage.status).toBe('fail');+ const {usage} = check('.', ['@acme/ui']);+ expect(usage.status).toBe('pass');+ expect(usage.message).toContain('@acme/ui');+ });++ it('passes built output that carries Astryx styles, minified', () => {+ write({+ 'dist/assets/app.css':+ '@layer reset,astryx-base,astryx-theme;@layer astryx-base{.x1{color:red}}',+ });++ const {usage, purity} = check('dist');+ expect(usage.status).toBe('pass');+ expect(usage.message).toContain('Astryx styles in assets/app.css');+ expect(purity.status).toBe('info');+ });++ it('reads a build folder inside a project for styles but never as source', () => {+ write({+ 'src/page.tsx': '<div />',+ '.next/static/chunk.js': 'var a="<div className=x>";',+ '.next/static/app.css': ':root{--astryx-layer-modal:10}',+ 'node_modules/@astryxdesign/core/index.js':+ "import '@astryxdesign/core';",+ });++ const scan = scanBuilt(dir, []);+ expect(scan.sourceFiles).toBe(1);+ expect(scan.stylesheets).toEqual(['.next/static/app.css']);+ expect(scan.imports).toBe(0);+ });++ it('fails a path that does not exist, saying nothing was checked', () => {+ const [usage, ...rest] = checkBuilt('missing', {cwd: dir, packages: []});+ expect(usage.status).toBe('fail');+ expect(usage.message).toContain('does not exist');+ expect(rest).toEqual([]);+ });+});++describe('built-astryx-purity', () => {+ it("names each finding of the rubric's source check with its file and line", () => {+ write({+ 'src/Page.tsx': [+ "import {VStack} from '@astryxdesign/core/VStack';",+ "import {Search} from 'lucide-react';",+ "import './page.css';",+ '// <div> in a comment is not a finding',+ 'export function Page() {',+ ' return (',+ ' <VStack>',+ ' <div className="row" style={{gap: 4}}>',+ ' <Search />',+ ' <svg viewBox="0 0 1 1"><path d="M0 0" /></svg>',+ ' <input type="hidden" name="x" />',+ ' </div>',+ ' </VStack>',+ ' );',+ '}',+ '',+ ].join('\n'),+ });++ const {usage, purity} = check('.');+ expect(usage.status).toBe('pass');+ expect(purity.status).toBe('warn');+ expect(purity.message).toMatch(/^6 findings/);+ expect(purity.message).toContain(+ 'src/Page.tsx:3 imports the stylesheet `./page.css`',+ );+ expect(purity.message).toContain('src/Page.tsx:8 raw `<div>`');+ expect(purity.message).toContain(+ 'src/Page.tsx:9 `<Search>` from an icon library',+ );+ // The message names the first five and counts the rest.+ expect(purity.message).toContain('and 1 more');+ const all = scanBuilt(dir, [])+ .findings.map(f => `${f.file}:${f.line} ${f.message}`)+ .join('\n');+ expect(all).toContain('src/Page.tsx:10 raw `<svg>`');+ // A helper's SVG counts once, and hidden form state keeps its element.+ expect(all).not.toContain('`<path>`');+ expect(all).not.toContain('`<input>`');+ expect(purity.fix).toContain('docs is-my-code-good');+ });++ it('passes source with no raw element, icon or custom style', () => {+ write({+ 'src/Page.tsx':+ "import {Text} from '@astryxdesign/core/Text';\nimport type {ReactNode} from 'react';\nexport const Page = (): ReactNode => <Text>Hi</Text>;\n",+ });++ expect(check('src').purity.status).toBe('pass');+ });+});++describe('what a --built path counts', () => {+ it('reads a bundle as build output: the source check says it was not inspected', () => {+ write({+ 'dist/assets/index.js':+ 'import "./a.css";import{jsx as e}from"react/jsx-runtime";export default()=>e("div",{className:"x"});',+ });+ const {purity} = check('dist');+ expect(purity.status).toBe('info');+ expect(purity.message).toContain('Not inspected');+ expect(purity.fix).toContain('doctor --built <project folder>');+ });++ it('inspects JSX in a .js source file and a .tsx file inside a folder named build', () => {+ write({+ 'src/page.js':+ 'export default function Page() {\n return <div>Hi</div>;\n}\n',+ 'src/build/Form.tsx': 'export const Form = () => <button>Go</button>;\n',+ });+ const scan = scanBuilt(path.join(dir, 'src'), []);+ expect(scan.jsxFiles).toBe(2);+ expect(scan.findings.map(f => `${f.file}:${f.message}`)).toEqual([+ 'build/Form.tsx:raw `<button>`: use `Button` or `IconButton`',+ 'page.js:raw `<div>`: use `VStack`, `HStack`, `Grid`, `Card`, `Section` or `Center`',+ ]);+ });++ it('keeps a side-effect import apart from the import after it', () => {+ write({+ 'src/Page.tsx':+ "import './page.css';\nimport {Button} from '@astryxdesign/core/Button';\nexport const Page = () => <Button label=\"Go\" />;\n",+ });+ const scan = scanBuilt(path.join(dir, 'src'), []);+ expect(scan.imports).toBe(1);+ expect(scan.componentUses).toBe(1);+ expect(scan.findings.map(f => f.message)).toContain(+ 'imports the stylesheet `./page.css`: use component props and tokens',+ );+ });++ it('names the integrations by the declared dependencies that ship a manifest, running nothing', () => {+ write({+ 'package.json': JSON.stringify({+ name: 'app',+ dependencies: {'@acme/ui': '1.0.0', 'left-pad': '1.0.0'},+ }),+ 'astryx.config.mjs':+ "import fs from 'node:fs';\nfs.writeFileSync(new URL('./ran.txt', import.meta.url), 'ran');\nexport default {};\n",+ 'node_modules/@acme/ui/package.json': '{"name":"@acme/ui"}',+ 'node_modules/@acme/ui/astryx.integration.mjs': 'export default {};\n',+ 'node_modules/left-pad/package.json': '{"name":"left-pad"}',+ 'out/index.html': '<p>x</p>',+ });+ expect(builtIntegrationPackages('out', dir)).toEqual(['@acme/ui']);+ expect(fs.existsSync(path.join(dir, 'ran.txt'))).toBe(false);+ });+});++describe('--built limits and speed', () => {+ it('finds an integration hoisted to the workspace root', () => {+ write({+ 'package.json': JSON.stringify({name: 'root', workspaces: ['apps/*']}),+ 'node_modules/@acme/ui/package.json': '{"name":"@acme/ui"}',+ 'node_modules/@acme/ui/astryx.integration.mjs': 'export default {};\n',+ 'apps/web/package.json': JSON.stringify({+ name: 'web',+ dependencies: {'@acme/ui': '1.0.0'},+ }),+ 'apps/web/out/index.html': '<p>x</p>',+ });+ expect(builtIntegrationPackages('apps/web/out', dir)).toEqual(['@acme/ui']);+ });++ it('says not fully inspected when a source file is over the size limit', () => {+ write({+ 'src/Page.tsx':+ "import {Text} from '@astryxdesign/core/Text';\nexport const Page = () => <Text>Hi</Text>;\n",+ 'src/Huge.tsx': `export const Huge = () => null;\n${'// x\n'.repeat(1_100_000)}`,+ });+ const {purity} = check('src');+ expect(purity.status).toBe('info');+ expect(purity.message).toContain('Not fully inspected');+ expect(purity.message).toContain('over 5 MB');+ });++ it('places findings in a large JSX file quickly', () => {+ const body = '<div>row</div>\n'.repeat(60_000);+ write({'src/Big.tsx': `export const Big = () => (\n<>\n${body}</>);\n`});+ const started = performance.now();+ const scan = scanBuilt(path.join(dir, 'src'), []);+ expect(scan.findings.length).toBe(60_000);+ expect(scan.findings.at(-1)?.line).toBe(60_002);+ expect(performance.now() - started).toBeLessThan(5_000);+ });+});++describe('--built edge cases', () => {+ it('reads the stylesheet a built page links when given the page alone', () => {+ write({+ 'dist/index.html':+ '<!doctype html><html><head><link rel="stylesheet" href="/assets/index.css"><script type="module" src="./assets/index.js"></script></head><body><div id="root"></div></body></html>',+ 'dist/assets/index.css': '@layer astryx-base{.x{color:red}}',+ 'dist/assets/index.js': 'console.log(1)',+ });+ const {usage} = check('dist/index.html');+ expect(usage.status).toBe('pass');+ expect(usage.message).toContain('Astryx styles in assets/index.css');+ });++ it('inspects a .js page whose JSX starts with a fragment', () => {+ write({+ 'src/page.js':+ 'export default function Page() {\n return (\n <>\n <div>Hi</div>\n </>\n );\n}\n',+ });+ const scan = scanBuilt(path.join(dir, 'src'), []);+ expect(scan.jsxFiles).toBe(1);+ expect(scan.findings).toHaveLength(1);+ });++ it('warns, not fails, when the file limit ends the read before any Astryx', () => {+ for (let i = 0; i < 20_001; i++) {+ const file = path.join(dir, 'a', String(i % 50), `${i}.txt`);+ fs.mkdirSync(path.dirname(file), {recursive: true});+ fs.writeFileSync(file, '');+ }+ const {usage} = check('.');+ expect(usage.status).toBe('warn');+ expect(usage.message).toContain('went unread');+ }, 60_000);++ it('finds a root-relative asset from the build root for a page in a subfolder', () => {+ write({+ 'dist/about/index.html':+ '<!doctype html><link rel="stylesheet" href="/assets/app.css"><div id="root"></div>',+ 'dist/assets/app.css': '@layer astryx-theme{.x{color:red}}',+ });+ expect(check('dist/about/index.html').usage.status).toBe('pass');+ });++ it('warns, not fails, when a page links a file that is not there', () => {+ write({+ 'out/index.html': '<link rel="stylesheet" href="./missing.css"><p>x</p>',+ });+ const {usage} = check('out/index.html');+ expect(usage.status).toBe('warn');+ expect(usage.message).toContain('not there');+ });++ it('inspects JSX in a .js file wherever it opens', () => {+ write({+ 'src/page.js':+ 'export const a = x || <div>A</div>;\nexport const b = [<span key="b">B</span>];\n',+ });+ const scan = scanBuilt(path.join(dir, 'src'), []);+ expect(scan.jsxFiles).toBe(1);+ expect(scan.findings).toHaveLength(2);+ });++ it('fails an empty folder as nothing checked, and warns when the only source is too big to read', () => {+ fs.mkdirSync(path.join(dir, 'empty'));+ expect(check('empty').usage.message).toContain('nothing was checked');+ write({+ 'big/Page.tsx': `import {Text} from '@astryxdesign/core/Text';\n${'// x\n'.repeat(1_100_000)}`,+ });+ const {usage} = check('big');+ expect(usage.status).toBe('warn');+ expect(usage.message).toContain('over 5 MB');+ });++ it('fails a page with no Astryx that links only a missing favicon', () => {+ write({+ 'out/index.html':+ '<link rel="icon" href="/favicon.ico"><link rel="manifest" href="/site.webmanifest"><p>x</p>',+ });+ expect(check('out/index.html').usage.status).toBe('fail');+ });++ it('survives a .js file with a huge array literal', () => {+ write({+ 'src/data.js': `export const rows = [${'0,'.repeat(200_000)}];\nexport const A = () => <p>x</p>;\n`,+ });+ const scan = scanBuilt(path.join(dir, 'src'), []);+ expect(scan.jsxFiles).toBe(1);+ });++ it('counts a .js file the parser cannot read as not inspected', () => {+ write({+ 'src/page.js':+ 'export default function Page() {\n return <div>{</div>;\n}\n@@@\n',+ });+ const {purity} = check('src');+ expect(purity.status).toBe('info');+ expect(purity.status).not.toBe('pass');+ });++ it('keeps JSX after a "/*" string, such as a splat route', () => {+ write({+ 'src/App.tsx':+ 'export const App = () => (\n <Route path="/*" element={<div>Home</div>} />\n);\n',+ });+ const scan = scanBuilt(path.join(dir, 'src'), []);+ expect(scan.findings.map(f => f.line)).toContain(2);+ });++ it('keeps JSX after a URL or a glob in JSX text', () => {+ write({+ 'src/page.js':+ 'export const A = () => (\n <section>\n <p>See https://example.com and src/*</p>\n <div>Box</div>\n </section>\n);\n',+ });+ const scan = scanBuilt(path.join(dir, 'src'), []);+ expect(scan.unread).toBe(0);+ expect(scan.findings.map(f => f.line)).toEqual(+ expect.arrayContaining([3, 4]),+ );+ });++ it('reads a page whose link attributes are unquoted', () => {+ write({+ 'dist/index.html':+ '<!doctype html><link rel=stylesheet href=/assets/index.css><div id=root></div>',+ 'dist/assets/index.css': '@layer astryx-base{.x{color:red}}',+ });+ expect(check('dist/index.html').usage.status).toBe('pass');+ });++ it('counts a barrel re-export and a CSS @import of an Astryx package', () => {+ write({+ 'src/ui.ts': "export {Button, Card} from '@astryxdesign/core';\n",+ 'src/index.css': "@import '@astryxdesign/core/styles.css';\n",+ });+ const {usage} = check('src');+ expect(usage.status).toBe('pass');+ expect(usage.message).toContain('@astryxdesign/core');+ });++ it('reads a .tsx with TypeScript and legacy decorators, and counts one nothing parses as unread', () => {+ write({+ 'src/Ok.tsx':+ 'function track(t: any) { return t; }\n@track\nclass Store { value!: string; }\nexport const A = () => <div>Hi</div>;\n',+ 'src/Broken.tsx': 'export const B = () => <div>{</div>;\n@@ enum ;\n',+ });+ const scan = scanBuilt(path.join(dir, 'src'), []);+ expect(scan.findings.filter(f => f.file === 'Ok.tsx')).toHaveLength(1);+ expect(scan.unread).toBe(1);+ expect(check('src').purity.status).not.toBe('pass');+ });++ it('does not count commented-out CSS as Astryx', () => {+ write({+ 'dist/index.css':+ "/* @import '@astryxdesign/core/styles.css'; */\n/* --astryx-color: red; */\n.x { color: red; }\n",+ });+ expect(check('dist').usage.status).toBe('fail');+ });++ it('does not count an import written only in a string or JSX text', () => {+ write({+ 'src/Page.tsx': [+ "const sample = `import {Button} from '@astryxdesign/core/Button';`;",+ 'export const Page = () => (',+ " <pre>import {Text} from '@astryxdesign/core/Text';</pre>",+ ');',+ '',+ ].join('\n'),+ });+ expect(check('src').usage.status).toBe('fail');+ });++ it('ignores a stylesheet link inside an HTML comment', () => {+ write({+ 'out/index.html':+ '<!-- <link rel="stylesheet" href="./astryx.css"> --><!-- <link rel="stylesheet" href="./gone.css"> --><p>x</p>',+ 'out/astryx.css': '@layer astryx-base{.x{color:red}}',+ });+ expect(check('out/index.html').usage.status).toBe('fail');+ });++ it('names unread source files in purity, with findings and without JSX', () => {+ write({+ 'src/Page.tsx': 'export const Page = () => <div>Hi</div>;\n',+ 'src/Broken.tsx': 'export const B = () => <div>{</div>;\n@@ enum ;\n',+ });+ const withFindings = check('src').purity;+ expect(withFindings.status).toBe('warn');+ expect(withFindings.message).toContain('not inspected: Broken.tsx');+ fs.rmSync(path.join(dir, 'src', 'Page.tsx'));+ const none = check('src').purity;+ expect(none.status).toBe('info');+ expect(none.message).toContain('Broken.tsx');+ });++ it('survives a file with more findings than a call can spread', () => {+ write({+ 'src/Rows.tsx': `export const Rows = () => (\n<>\n${'<p/>\n'.repeat(200_000)}</>);\n`,+ });+ const scan = scanBuilt(path.join(dir, 'src'), []);+ expect(scan.findings.length).toBe(200_000);+ });+});++describe('doctor --built', () => {+ it('composes with --json: one envelope with the two checks last, exit 1 on a failed build', async () => {+ write({'out/index.html': '<div>no astryx</div>'});+ const result = await runCli(['--json', 'doctor', '--built', 'out'], dir);+ const envelope = JSON.parse(result.stdout);+ const ids = envelope.data.checks.map(+ (/** @type {{id: string}} */ c) => c.id,+ );+ expect(ids.slice(-2)).toEqual([+ 'built-astryx-usage',+ 'built-astryx-purity',+ ]);+ expect(result.status).toBe(1);+ }, 60_000);++ it('adds the two checks after the others, and plain doctor runs without them', async () => {+ write({'out/index.html': '<div>no astryx</div>'});++ const plain = await runChecks({cwd: dir});+ const built = await runChecks({cwd: dir, built: 'out'});++ expect(plain.checks.some(c => c.id.startsWith('built-'))).toBe(false);+ expect(built.checks.map(c => c.id)).toEqual([+ ...plain.checks.map(c => c.id),+ 'built-astryx-usage',+ 'built-astryx-purity',+ ]);+ expect(built.summary.fail).toBe(plain.summary.fail + 1);+ });+});diff --git a/packages/cli/api/doctor/doctor.doc.mjs b/packages/cli/api/doctor/doctor.doc.mjsindex 175b65785c..dd12045de4 100644--- a/packages/cli/api/doctor/doctor.doc.mjs+++ b/packages/cli/api/doctor/doctor.doc.mjs@@ -37,6 +37,12 @@ export const doc = {'Directory to diagnose. A directory outside any project, a missing one included, gets the computer checks.',default: 'process.cwd()',},+ {+ name: 'options.built',+ type: 'string',+ description:+ 'A finished build to check before you deliver it: a project folder, a build output folder, or one built `.html` file, relative to `cwd`. Adds two checks after the others. `built-astryx-usage` fails when the path holds no import from an Astryx package (any `@astryxdesign/*` package or an integration the project installs), no component imported from one, and no Astryx styles in built CSS or HTML. `built-astryx-purity` warns with the source check of `astryx docs is-my-code-good`: raw elements Astryx has a component for, raw SVG and icon-library icons, inline styles, classes, `stylex.create` and imported stylesheets, each with its file and line, in `.tsx` and `.jsx` files and JSX in `.js` source, found by parsing it; it is info, not inspected, when the path holds no source with JSX, such as a bundle. It reads at most 20,000 files, each up to 5 MB, skipping installs and version control; when either limit leaves source unread and nothing was found, the purity check is info, not fully inspected, and when the file limit ends the read before any Astryx turns up, `built-astryx-usage` warns that the rest went unread instead of failing. Given one built `.html` file, it also reads the local stylesheets and scripts that page links, finding a root-relative link from the nearest folder above the page that holds it; a linked file that is not there makes `built-astryx-usage` warn instead of fail. An empty folder fails with nothing checked, like a missing path. A source tree counts as using Astryx through an import, a re-export (`export … from`) or a stylesheet `@import` of an Astryx package. `--built` goes with `doctor` alone; a `doctor integration` check refuses it. A path that does not exist fails `built-astryx-usage` with nothing checked, and the purity check is left out. The integrations that count are the dependencies the nearest package.json above the path declares whose installed copy, found the way the CLI autolinks (a hoisted workspace copy included), has an integration manifest. The files under the path, and that configuration, are only read, never run. Without it, doctor runs exactly as before.',+ },],returns: [{@@ -54,6 +60,10 @@ export const doc = {label: 'Diagnose a directory',code: "await doctor({cwd: '/path/to/app'});",},+ {+ label: 'Check a finished build before delivering it',+ code: "const r = await doctor({built: 'dist'});\nif (r.data.summary.fail > 0) throw new Error('Not built with Astryx');",+ },],command: 'doctor',related: ['init', 'upgrade'],diff --git a/packages/cli/api/doctor/doctor.mjs b/packages/cli/api/doctor/doctor.mjsindex 16e76a4f2a..b7ea1c0f96 100644--- a/packages/cli/api/doctor/doctor.mjs+++ b/packages/cli/api/doctor/doctor.mjs@@ -67,7 +67,8 @@ import {semverCompare, isValidSemver, satisfiesRange} from '../../foundation/envimport {checkAppThemes, checkThemes} from './theme-checks.mjs';import {availableLine, RUN_FROM_PROJECT, upgradeLine} from '../../foundation/release/notices.mjs';import {COMPUTER_COMMAND, COMPUTER_INSTALL_STEP} from '../../foundation/agent-docs/computer-agent-text.mjs';-import {alignCommand, addCliCommandFor, computerAgentTextState, installCommandFor, insideProjectElsewhere, projectCoreVersion, projectHasOwnCli, computerIntegrationsOutside, computerIntegrationsToAdd, displayHomePath, outsideProject, releaseFacts} from './_adapter.mjs';+import {alignCommand, addCliCommandFor, computerAgentTextState, installCommandFor, insideProjectElsewhere, projectCoreVersion, projectHasOwnCli, computerIntegrationsOutside, computerIntegrationsToAdd, displayHomePath, outsideProject, releaseFacts, builtIntegrationPackages} from './_adapter.mjs';+import {checkBuilt} from './built-checks.mjs';/*** @typedef {'pass'|'warn'|'fail'|'info'} DoctorStatus@@ -1910,9 +1911,24 @@ export const SYNC_CHECKS = [** @param {object} [options]* @param {string} [options.cwd] - Directory to diagnose (default: process.cwd()).+ * @param {string} [options.built] - A finished build to check for Astryx+ * use: a project folder, a build output folder, or one built file+ * (built-checks.mjs). Without it, the checks are unchanged.* @returns {Promise<DoctorReport>}*/export async function runChecks(options = {}) {+ if (options.built != null) {+ const {built, ...rest} = options;+ const report = await runChecks(rest);+ const cwd = rest.cwd ?? process.cwd();+ const checks = [+ ...report.checks,+ ...checkBuilt(built, {cwd, packages: builtIntegrationPackages(built, cwd)}),+ ];+ const summary = {pass: 0, warn: 0, fail: 0, info: 0};+ for (const c of checks) summary[c.status] += 1;+ return {checks, summary};+ }const cwd = options.cwd ?? process.cwd();if (outsideProject(cwd)) return runComputerChecks(cwd);const coreDir = findProjectCoreDir(cwd);@@ -2120,8 +2136,7 @@ export async function runChecks(options = {}) {* Programmatic API: run the doctor and return the same envelope shape that* `astryx doctor --json` emits.*- * @param {object} [options]- * @param {string} [options.cwd]+ * @param {import('./doctor.type.mjs').DoctorOptions} [options]* @returns {Promise<{type: 'doctor', data: DoctorReport}>}*/export async function doctor(options = {}) {diff --git a/packages/cli/api/doctor/doctor.type.mjs b/packages/cli/api/doctor/doctor.type.mjsindex f166be436b..81564e3729 100644--- a/packages/cli/api/doctor/doctor.type.mjs+++ b/packages/cli/api/doctor/doctor.type.mjs@@ -44,6 +44,9 @@* Options for `doctor()`.* @typedef {object} DoctorOptions* @property {string} [cwd]+ * @property {string} [built] A finished build to check for Astryx use: a+ * project folder, a build output folder, or one built file. Adds the+ * `built-astryx-usage` and `built-astryx-purity` checks.*/export {};diff --git a/packages/cli/clients/cli/commands/doctor.doc.mjs b/packages/cli/clients/cli/commands/doctor.doc.mjsindex ae02d51e74..7c163cfad7 100644--- a/packages/cli/clients/cli/commands/doctor.doc.mjs+++ b/packages/cli/clients/cli/commands/doctor.doc.mjs@@ -25,9 +25,21 @@ export const doc = {'It never fails a check because the folder has no project.',fn: 'doctor',subcommands: ['integration'],+ options: [+ {+ flag: '--built <path>',+ param: 'options.built',+ description:+ 'Also check a finished build before you deliver it: a project folder, a build output folder, or one built HTML file. Fails when it does not use Astryx at all, and warns with each raw element, icon or custom style in its source.',+ },+ ],examples: [{label: 'Run project diagnostics', cli: 'astryx doctor'},{label: 'Machine-readable project report', cli: 'astryx doctor --json'},+ {+ label: 'Before you deliver a build: check that it uses Astryx',+ cli: 'astryx doctor --built dist',+ },{label: 'Validate an integration',cli: 'astryx doctor integration validate @acme/widgets',diff --git a/packages/cli/clients/cli/commands/doctor.mjs b/packages/cli/clients/cli/commands/doctor.mjsindex c24cb741e8..9ec7c8b8de 100644--- a/packages/cli/clients/cli/commands/doctor.mjs+++ b/packages/cli/clients/cli/commands/doctor.mjs@@ -563,9 +563,14 @@ export function printIntegrationCheckResponse(response) {}}-/** @param {import('commander').Command} program */-async function runProjectDoctor(program) {- const report = await runChecks();+/**+ * @param {import('commander').Command} program+ * @param {{built?: string}} [options]+ */+async function runProjectDoctor(program, options = {}) {+ const report = await runChecks(+ options.built != null ? {built: options.built} : {},+ );if (program.opts().json) jsonOut({type: 'doctor', data: report});else printHuman(report);if (report.summary.fail > 0) process.exitCode = 1;@@ -689,7 +694,7 @@ export function registerDoctor(program) {action: async (options, invoked) => {const word = unknownWord(invoked);if (word != null) return unknownSubcommand(doctorCmd, 'doctor', word);- return runProjectDoctor(program);+ return runProjectDoctor(program, options);},});/** @type {import('commander').Command} */@@ -704,20 +709,30 @@ export function registerDoctor(program) {return NO_RESULT_SET;},});+ // `--built` checks a project's build; an integration check has none.+ const refuseBuilt = () =>+ doctorCmd.opts().built != null+ ? cliError(+ '`--built` checks a finished build and goes with `doctor` alone, not with a `doctor integration` check',+ {code: ERROR_CODES.ERR_INVALID_OPTION},+ )+ : null;defineCommand(integrationCmd, doctorIntegrationValidateCommand, {fn: validateIntegrationFn,- action: async pkg => runIntegrationValidation(program, pkg),+ action: async pkg => refuseBuilt() ?? runIntegrationValidation(program, pkg),});defineCommand(integrationCmd, doctorIntegrationTemplatesCommand, {fn: integrationTemplateConflictsFn,- action: async pkg => runAuthoringCheck(program, pkg, 'templates'),+ action: async pkg =>+ refuseBuilt() ?? runAuthoringCheck(program, pkg, 'templates'),});defineCommand(integrationCmd, doctorIntegrationComponentsCommand, {fn: integrationComponentConflictsFn,- action: async pkg => runAuthoringCheck(program, pkg, 'components'),+ action: async pkg =>+ refuseBuilt() ?? runAuthoringCheck(program, pkg, 'components'),});defineCommand(integrationCmd, doctorIntegrationDocsCommand, {fn: integrationDocConflictsFn,- action: async pkg => runAuthoringCheck(program, pkg, 'docs'),+ action: async pkg => refuseBuilt() ?? runAuthoringCheck(program, pkg, 'docs'),});}diff --git a/packages/cli/foundation/response/error-codes.test.mjs b/packages/cli/foundation/response/error-codes.test.mjsindex 2b574dc70e..4f1658b238 100644--- a/packages/cli/foundation/response/error-codes.test.mjs+++ b/packages/cli/foundation/response/error-codes.test.mjs@@ -258,6 +258,15 @@ describe('error codes: human mode stays clean', () => {expect(stdout).not.toContain('ERR_UNKNOWN_COMPONENT');});+ it('refuses --built with a doctor integration check', async () => {+ const json = await runCli(['--json', 'doctor', '--built', 'dist', 'integration', 'validate']);+ expect(json.status).toBe(1);+ expect(JSON.parse(json.stdout)).toMatchObject({code: 'ERR_INVALID_OPTION'});+ const text = await runCli(['doctor', '--built', 'dist', 'integration', 'docs']);+ expect(text.status).toBe(1);+ expect(text.stderr).toContain('goes with `doctor` alone');+ });+it('unknown subcommand exits 1, with the code in JSON and not in text', async () => {// A group that is not JSON-capable itself still answers an unknown// subcommand in JSON, so a JSON caller learns the subcommands it has.