An open source design system that's fully customizable and agent ready
TypeScript
feat: unify component audit roster (#6105)
Cindy Zhangcd70861fbd70
diff --git a/.github/scripts/change-scope.test.mjs b/.github/scripts/change-scope.test.mjsindex 9fae95f040..1ff270f3a9 100644--- a/.github/scripts/change-scope.test.mjs+++ b/.github/scripts/change-scope.test.mjs@@ -20,6 +20,9 @@ describe('spec-only change scope', () => {'packages/core/src/Table/plugins/rowStatus/useTableRowStatus.spec.md',},{filename: 'packages/lab/src/FutureInput/FutureInput.spec.md'},+ {filename: 'packages/charts/src/Chart.spec.md'},+ {filename: 'packages/richtext/src/RichTextView.spec.md'},+ {filename: 'packages/vega/src/VegaChart.spec.md'},]);expect(result.specOnly).toBe(true);});diff --git a/.github/scripts/knowledge-paths.cjs b/.github/scripts/knowledge-paths.cjsindex 72431115e7..1ec206fbe5 100644--- a/.github/scripts/knowledge-paths.cjs+++ b/.github/scripts/knowledge-paths.cjs@@ -1,14 +1,20 @@// Copyright (c) Meta Platforms, Inc. and affiliates.'use strict';-/* global module */+/* global module, require *//**- * One dependency-free path contract for component-local knowledge records.- * Validation, change classification, and the spec-owner gate all consume this- * helper so ignored paths cannot become records on only one surface.+ * One shared path contract for component-local knowledge records. It consumes+ * the component-package registry so validation, change classification, and the+ * spec-owner gate cannot disagree about supported package layouts.*/+// eslint-disable-next-line @typescript-eslint/no-require-imports+const {+ COMPONENT_PACKAGE_NAMES,+ componentPackage,+} = require('../../scripts/component-packages.cjs');+const IGNORED_COMPONENT_KNOWLEDGE_SEGMENTS = new Set(['__fixtures__','__generated__',@@ -37,33 +43,50 @@ function isIgnoredComponentKnowledgeSegment(segment) {/*** Classify a canonical component-local knowledge candidate by path alone.- * Direct children are component-record candidates; module records must be- * nested at least one directory beneath the component root. Semantic kind,- * filename/id agreement, and parent ownership are validated after parsing.+ * Directory-layout component records are direct children of a component root;+ * flat-package component records are direct children of src. Module records are+ * nested below either component boundary. Semantic kind, filename/id agreement,+ * and parent ownership are validated after parsing.*/function classifyComponentKnowledgePath(filePath) {const normalized = normalizePath(filePath);- const match = /^packages\/(core|lab)\/src\/([^/]+)\/(.+\.spec\.md)$/.exec(- normalized,- );+ const match = /^packages\/([^/]+)\/src\/(.+\.spec\.md)$/.exec(normalized);if (!match) return null;const packageName = match[1];- const componentRoot = match[2];- const relativePath = match[3];- const segments = [componentRoot, ...relativePath.split('/')];- if (segments.some(isIgnoredComponentKnowledgeSegment)) return null;+ const packageConfig = componentPackage(packageName);+ if (!packageConfig) return null;- const fileName = segments.at(-1);+ const packageRelativePath = match[2];+ const packageSegments = packageRelativePath.split('/');+ if (packageSegments.some(isIgnoredComponentKnowledgeSegment)) return null;++ const fileName = packageSegments.at(-1);if (fileName.endsWith('.generated.spec.md')) return null;const publicName = fileName.slice(0, -'.spec.md'.length);if (!/^[A-Za-z][A-Za-z0-9]*$/.test(publicName)) return null;- const nested = relativePath.includes('/');+ if (packageConfig.layout === 'flat') {+ const nested = packageSegments.length > 1;+ return {+ componentRoot: nested ? packageSegments[0] : publicName,+ fileName,+ kind: nested ? 'module' : 'component',+ layout: packageConfig.layout,+ packageName,+ publicName,+ relativePath: packageRelativePath,+ };+ }++ if (packageSegments.length < 2) return null;+ const componentRoot = packageSegments[0];+ const relativePath = packageSegments.slice(1).join('/');return {componentRoot,fileName,- kind: nested ? 'module' : 'component',+ kind: relativePath.includes('/') ? 'module' : 'component',+ layout: packageConfig.layout,packageName,publicName,relativePath,@@ -75,6 +98,7 @@ function isComponentSpecRecordPath(filePath) {}module.exports = {+ COMPONENT_PACKAGE_NAMES,IGNORED_COMPONENT_KNOWLEDGE_SEGMENTS,classifyComponentKnowledgePath,isComponentSpecRecordPath,diff --git a/.github/scripts/knowledge-paths.test.mjs b/.github/scripts/knowledge-paths.test.mjsindex 91d582cfae..e1fd98fc87 100644--- a/.github/scripts/knowledge-paths.test.mjs+++ b/.github/scripts/knowledge-paths.test.mjs@@ -12,23 +12,38 @@ const {describe('component knowledge paths', () => {it.each([[- 'flat component record',+ 'directory-layout Core component record','packages/core/src/Button/Button.spec.md','component',],[- 'flat public member record',+ 'directory-layout public member record','packages/core/src/NavMenu/NavHeadingMenu.spec.md','component',],[- 'nested module record',+ 'directory-layout module record','packages/core/src/Table/plugins/rowStatus/useTableRowStatus.spec.md','module',],[- 'nested Lab module record',- 'packages/lab/src/Future/subsystems/model/createModel.spec.md',+ 'flat Charts component record',+ 'packages/charts/src/Chart.spec.md',+ 'component',+ ],+ [+ 'flat Rich Text component record',+ 'packages/richtext/src/RichTextView.spec.md',+ 'component',+ ],+ [+ 'flat Vega component record',+ 'packages/vega/src/VegaChart.spec.md',+ 'component',+ ],+ [+ 'flat-package module record',+ 'packages/charts/src/Chart/plugins/useChartSelection.spec.md','module',],])('classifies the %s', (_label, filePath, kind) => {@@ -53,7 +68,8 @@ describe('component knowledge paths', () => {'packages/core/src/Button/Button.md','packages/core/src/Button/not-kebab.spec.md','packages/core/src/Button.spec.md',- 'packages/charts/src/Chart/Chart.spec.md',+ 'packages/themes/neutral/src/Button.spec.md',+ 'packages/cli/src/Prompt.spec.md',])('rejects non-record path %s', filePath => {expect(classifyComponentKnowledgePath(filePath)).toBeNull();});diff --git a/.github/scripts/spec-owner-workflow.test.mjs b/.github/scripts/spec-owner-workflow.test.mjsindex 6d442fe84b..b1de4d25d9 100644--- a/.github/scripts/spec-owner-workflow.test.mjs+++ b/.github/scripts/spec-owner-workflow.test.mjs@@ -41,7 +41,10 @@ describe('spec-only workflow contract', () => {'git show "origin/${{ github.base_ref }}:.github/scripts/knowledge-paths.cjs"',);expect(source, workflow).toContain(- 'CLASSIFIER_DIR="$RUNNER_TEMP/change-scope"',+ 'git show "origin/${{ github.base_ref }}:scripts/component-packages.cjs"',+ );+ expect(source, workflow).toContain(+ 'CLASSIFIER_ROOT="$RUNNER_TEMP/change-scope"',);}@@ -49,16 +52,24 @@ describe('spec-only workflow contract', () => {path.join(os.tmpdir(), 'astryx-change-scope-'),);try {+ const classifierDir = path.join(isolated, '.github/scripts');+ const registryDir = path.join(isolated, 'scripts');+ fs.mkdirSync(classifierDir, {recursive: true});+ fs.mkdirSync(registryDir, {recursive: true});for (const file of ['change-scope.cjs', 'knowledge-paths.cjs']) {fs.copyFileSync(path.join(root, '.github/scripts', file),- path.join(isolated, file),+ path.join(classifierDir, file),);}+ fs.copyFileSync(+ path.join(root, 'scripts/component-packages.cjs'),+ path.join(registryDir, 'component-packages.cjs'),+ );const output = path.join(isolated, 'github-output');const result = spawnSync(process.execPath,- [path.join(isolated, 'change-scope.cjs'), '--github-output'],+ [path.join(classifierDir, 'change-scope.cjs'), '--github-output'],{encoding: 'utf8',env: {...process.env, GITHUB_OUTPUT: output},@@ -71,10 +82,10 @@ describe('spec-only workflow contract', () => {'spec_only=true\ndocsite_only=false\n',);- fs.rmSync(path.join(isolated, 'knowledge-paths.cjs'));+ fs.rmSync(path.join(classifierDir, 'knowledge-paths.cjs'));const missingDependency = spawnSync(process.execPath,- [path.join(isolated, 'change-scope.cjs')],+ [path.join(classifierDir, 'change-scope.cjs')],{encoding: 'utf8',input: 'A\tpackages/core/src/Button/Button.spec.md\n',diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex b341a057e2..cbbacf8a6d 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -48,12 +48,16 @@ jobs:printf 'docsite_only=false\nspec_only=false\n' >> "$GITHUB_OUTPUT"exit 0fi- CLASSIFIER_DIR="$RUNNER_TEMP/change-scope"- mkdir -p "$CLASSIFIER_DIR"+ CLASSIFIER_ROOT="$RUNNER_TEMP/change-scope"+ CLASSIFIER_DIR="$CLASSIFIER_ROOT/.github/scripts"+ REGISTRY_DIR="$CLASSIFIER_ROOT/scripts"+ mkdir -p "$CLASSIFIER_DIR" "$REGISTRY_DIR"CLASSIFIER="$CLASSIFIER_DIR/change-scope.cjs"MATCHER="$CLASSIFIER_DIR/knowledge-paths.cjs"+ REGISTRY="$REGISTRY_DIR/component-packages.cjs"if git show "origin/${{ github.base_ref }}:.github/scripts/change-scope.cjs" > "$CLASSIFIER" 2>/dev/null \- && git show "origin/${{ github.base_ref }}:.github/scripts/knowledge-paths.cjs" > "$MATCHER" 2>/dev/null; then+ && git show "origin/${{ github.base_ref }}:.github/scripts/knowledge-paths.cjs" > "$MATCHER" 2>/dev/null \+ && git show "origin/${{ github.base_ref }}:scripts/component-packages.cjs" > "$REGISTRY" 2>/dev/null; thengit diff --name-status "$MERGE_BASE"...HEAD \| node "$CLASSIFIER" --github-outputelsediff --git a/.github/workflows/lint.yml b/.github/workflows/lint.ymlindex 24653372d7..8a19357b4b 100644--- a/.github/workflows/lint.yml+++ b/.github/workflows/lint.yml@@ -29,12 +29,16 @@ jobs:printf 'docsite_only=false\nspec_only=false\n' >> "$GITHUB_OUTPUT"exit 0fi- CLASSIFIER_DIR="$RUNNER_TEMP/change-scope"- mkdir -p "$CLASSIFIER_DIR"+ CLASSIFIER_ROOT="$RUNNER_TEMP/change-scope"+ CLASSIFIER_DIR="$CLASSIFIER_ROOT/.github/scripts"+ REGISTRY_DIR="$CLASSIFIER_ROOT/scripts"+ mkdir -p "$CLASSIFIER_DIR" "$REGISTRY_DIR"CLASSIFIER="$CLASSIFIER_DIR/change-scope.cjs"MATCHER="$CLASSIFIER_DIR/knowledge-paths.cjs"+ REGISTRY="$REGISTRY_DIR/component-packages.cjs"if git show "origin/${{ github.base_ref }}:.github/scripts/change-scope.cjs" > "$CLASSIFIER" 2>/dev/null \- && git show "origin/${{ github.base_ref }}:.github/scripts/knowledge-paths.cjs" > "$MATCHER" 2>/dev/null; then+ && git show "origin/${{ github.base_ref }}:.github/scripts/knowledge-paths.cjs" > "$MATCHER" 2>/dev/null \+ && git show "origin/${{ github.base_ref }}:scripts/component-packages.cjs" > "$REGISTRY" 2>/dev/null; thengit diff --name-status "$MERGE_BASE"...HEAD \| node "$CLASSIFIER" --github-outputelsediff --git a/apps/sandbox/scripts/generate-score-ledger.mjs b/apps/sandbox/scripts/generate-score-ledger.mjsindex be6220f21b..6006bb879f 100644--- a/apps/sandbox/scripts/generate-score-ledger.mjs+++ b/apps/sandbox/scripts/generate-score-ledger.mjs@@ -3,10 +3,11 @@/*** @file generate-score-ledger.mjs* @description Generates apps/sandbox/src/generated/componentScores.ts — the- * ROSTER of components (read from the ledger packages — core, lab and- * richtext — by the canonical predicate in scripts/score-ledger.mjs) plus a- * build-time SNAPSHOT of the audit ledger fetched from the wiki.- * @input packages/{core,lab,richtext}/src, and the wiki ledger over the network.+ * ROSTER of public components (read from every component-bearing package in+ * scripts/component-packages.cjs by the canonical predicate in+ * scripts/score-ledger.mjs) plus a build-time SNAPSHOT of the wiki ledger.+ * @input Registered component-package source roots and the wiki ledger over the+ * network.* @output src/generated/componentScores.ts* @position Sandbox build step, run by `pnpm generate`.*@@ -212,8 +213,9 @@ const banner = `// Copyright (c) Meta Platforms, Inc. and affiliates.* GENERATED FILE — do not edit.* Regenerate: node apps/sandbox/scripts/generate-score-ledger.mjs*- * \`roster\` is read from packages/{core,lab,richtext}/src by the canonical component- * predicate. \`snapshot\` is a build-time copy of the wiki ledger, used only+ * \`roster\` is read from every component-bearing package registered in+ * scripts/component-packages.cjs. \`snapshot\` is a build-time copy of the wiki+ * ledger, used only* until the page's runtime fetch of LEDGER_URL resolves.*/`;@@ -312,7 +314,7 @@ export const SECTION_TITLES: Record<string, string> = ${JSON.stringify(SECTION_Texport const SECTION_WEIGHTS: Record<string, number> = ${JSON.stringify(SECTION_WEIGHTS, null, 2)};-/** Every component in packages/{core,lab,richtext}/src, by the canonical predicate. */+/** Every component in the registered component-package source roots. */export const roster: RosterEntry[] = ${JSON.stringify(roster, null, 2)};/**diff --git a/docs/README.md b/docs/README.mdindex 00b36731ea..0923d1d4ec 100644--- a/docs/README.md+++ b/docs/README.md@@ -15,11 +15,19 @@ it governs. Consumer documentation remains in component `.doc.mjs` files and- `templates/knowledge/`: authoring templates. Templates never live among records.- `schemas/knowledge/`: versioned structural requirements for templates and records.-Component contracts are direct children of their Core or Lab component root and-use `<PublicName>.spec.md`. `<PublicName>` normally matches the root directory;+Component contracts live beside the public component in every component-bearing+package registered by `scripts/component-packages.cjs`:++- directory-layout packages (`core`, `lab`) use+ `packages/<package>/src/<ComponentRoot>/<PublicName>.spec.md`;+- flat packages (`charts`, `richtext`, `vega`) use+ `packages/<package>/src/<PublicName>.spec.md`.++In a directory-layout package, `<PublicName>` normally matches the root directory;a public member such as `NavMenu/NavHeadingMenu.spec.md` is valid only when anexact top-level or full inline consumer-doc entry in that root declares the same-public name. A flat filename and matching `component:` id alone are not enough.+public name. In a flat package, the public named export and matching TSX module+define the component boundary.Independently contractible public hooks, plugins, utilities, and subsystems use`kind: module` records named `<PublicName>.spec.md` at least one directory belowdiff --git a/scripts/check-knowledge.mjs b/scripts/check-knowledge.mjsindex 32c81f45a8..38e5ad75f6 100644--- a/scripts/check-knowledge.mjs+++ b/scripts/check-knowledge.mjs@@ -9,6 +9,10 @@ import {fileURLToPath} from 'node:url';import {collectThemingTargets} from '../packages/cli/foundation/discovery/theming-targets.mjs';const require = createRequire(import.meta.url);+const {+ COMPONENT_PACKAGE_NAMES,+ packageHasPublicComponent,+} = require('./component-packages.cjs');const {parseAuthority,parseOwnerFile,@@ -205,7 +209,7 @@ export function discoverKnowledgeRecords(root = DEFAULT_ROOT) {records.push(...discoverThemeRecordCandidates(root).records);- for (const packageName of ['core', 'lab']) {+ for (const packageName of COMPONENT_PACKAGE_NAMES) {const sourceRoot = path.join(root, `packages/${packageName}/src`);records.push(...matchingFilesRecursively(@@ -235,6 +239,16 @@ function componentRecordLocation(root, absolutePath) {'src',classified.componentRoot,),+ componentSourcePath:+ classified.layout === 'flat'+ ? path.join(root, 'packages', classified.packageName, 'src')+ : path.join(+ root,+ 'packages',+ classified.packageName,+ 'src',+ classified.componentRoot,+ ),};}@@ -313,7 +327,7 @@ export function validateComponentModuleRelationships(const location = componentRecordLocation(root, record.absolutePath);if (!location) {problems.push(- `${record.filePath}: ${kind} records must live under packages/{core,lab}/src/<component-root>/.`,+ `${record.filePath}: ${kind} records must live under a registered component package source root.`,);continue;}@@ -331,10 +345,18 @@ export function validateComponentModuleRelationships(`${record.filePath}: component record id must be ${expectedId} to match its filename.`,);}+ if (+ location.layout === 'flat' &&+ !packageHasPublicComponent(root, location.packageName, publicName)+ ) {+ problems.push(+ `${record.filePath}: flat-package component record ${expectedId} must match a public named export and TSX module in packages/${location.packageName}/src.`,+ );+ }if (publicName !== location.componentRoot &&!componentRootDefinesPublicComponent(- location.componentRootPath,+ location.componentSourcePath,publicName,)) {@@ -354,6 +376,11 @@ export function validateComponentModuleRelationships(const idMatch = typeof id === 'string' ? MODULE_ID_PATTERN.exec(id) : null;if (!idMatch) continue;const expectedParent = `component:${idMatch[1]}`;+ if (location.layout === 'flat' && location.componentRoot !== idMatch[1]) {+ problems.push(+ `${record.filePath}: flat-package module ${id} must live under packages/${location.packageName}/src/${idMatch[1]}/ to match its parent component.`,+ );+ }if (frontmatter.get('parent_component') !== expectedParent) {problems.push(`${record.filePath}: parent_component must be ${expectedParent} to match module id ${id}.`,@@ -835,7 +862,7 @@ function loadModuleContract(root, specPath, moduleName) {const candidates = [];for (const docPath of matchingFilesRecursively(- location.componentRootPath,+ location.componentSourcePath,name => name.endsWith('.doc.mjs'),{skipDirectory: isIgnoredComponentKnowledgeSegment},)) {diff --git a/scripts/check-knowledge.test.mjs b/scripts/check-knowledge.test.mjsindex 311eabbea1..ede6be8195 100644--- a/scripts/check-knowledge.test.mjs+++ b/scripts/check-knowledge.test.mjs@@ -41,6 +41,9 @@ function fixtureRoot() {'docs/themes','packages/core/src','packages/lab/src',+ 'packages/charts/src',+ 'packages/richtext/src',+ 'packages/vega/src',]) {fs.mkdirSync(path.join(root, relative), {recursive: true});}@@ -794,6 +797,108 @@ describe('knowledge validation', () => {expect(await validateKnowledgeRoot(root)).toEqual([]);});+ it('accepts a draft component record in a flat component package', async () => {+ const root = fixtureRoot();+ const directory = path.join(root, 'packages/vega/src');+ fs.writeFileSync(+ path.join(directory, 'index.ts'),+ "export {VegaChart} from './VegaChart';\n",+ );+ fs.writeFileSync(+ path.join(directory, 'VegaChart.tsx'),+ 'export function VegaChart() {}\n',+ );+ fs.writeFileSync(+ path.join(directory, 'VegaChart.spec.md'),+ componentRecord({id: 'component:VegaChart'}),+ );+ expect(await validateKnowledgeRoot(root)).toEqual([]);+ });++ it('rejects a flat-package spec with no matching public component', async () => {+ const root = fixtureRoot();+ const directory = path.join(root, 'packages/charts/src');+ fs.writeFileSync(+ path.join(directory, 'index.ts'),+ "export {Chart} from './Chart';\n",+ );+ fs.writeFileSync(+ path.join(directory, 'Chart.tsx'),+ 'export function Chart() {}\n',+ );+ fs.writeFileSync(+ path.join(directory, 'Ghost.spec.md'),+ componentRecord({id: 'component:Ghost'}),+ );+ expect((await validateKnowledgeRoot(root)).join('\n')).toMatch(+ /must match a public named export and TSX module/,+ );+ });++ it('accepts a flat-package module beneath its declared parent component', async () => {+ const root = fixtureRoot();+ const source = path.join(root, 'packages/charts/src');+ const modulePath = path.join(source, 'Chart/plugins/useChartThing.spec.md');+ fs.mkdirSync(path.dirname(modulePath), {recursive: true});+ fs.writeFileSync(+ path.join(source, 'index.ts'),+ "export {Chart} from './Chart';\n",+ );+ fs.writeFileSync(+ path.join(source, 'Chart.tsx'),+ 'export function Chart() {}\n',+ );+ fs.writeFileSync(+ path.join(source, 'Chart.spec.md'),+ componentRecord({+ id: 'component:Chart',+ modules: '[module:Chart/useChartThing]',+ }),+ );+ fs.writeFileSync(+ modulePath,+ moduleRecord({+ id: 'module:Chart/useChartThing',+ parent_component: 'component:Chart',+ }),+ );++ expect(await validateKnowledgeRoot(root)).toEqual([]);+ });++ it('rejects a flat-package module beneath a different path root', async () => {+ const root = fixtureRoot();+ const source = path.join(root, 'packages/charts/src');+ const modulePath = path.join(source, 'Ghost/plugins/useChartThing.spec.md');+ fs.mkdirSync(path.dirname(modulePath), {recursive: true});+ fs.writeFileSync(+ path.join(source, 'index.ts'),+ "export {Chart} from './Chart';\n",+ );+ fs.writeFileSync(+ path.join(source, 'Chart.tsx'),+ 'export function Chart() {}\n',+ );+ fs.writeFileSync(+ path.join(source, 'Chart.spec.md'),+ componentRecord({+ id: 'component:Chart',+ modules: '[module:Chart/useChartThing]',+ }),+ );+ fs.writeFileSync(+ modulePath,+ moduleRecord({+ id: 'module:Chart/useChartThing',+ parent_component: 'component:Chart',+ }),+ );++ expect((await validateKnowledgeRoot(root)).join('\n')).toMatch(+ /flat-package module module:Chart\/useChartThing must live under packages\/charts\/src\/Chart\//,+ );+ });+it('accepts a flat public member record backed by the root consumer doc', async () => {const root = fixtureRoot();const directory = path.join(root, 'packages/core/src/NavMenu');diff --git a/scripts/component-packages.cjs b/scripts/component-packages.cjsnew file mode 100644index 0000000000..01e2057ef1--- /dev/null+++ b/scripts/component-packages.cjs@@ -0,0 +1,218 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use strict';+/* global module, require */++/**+ * @file Shared registry of component-bearing Astryx packages and their layouts.+ * @input Repository package names, source roots, public barrels, and component docs.+ * @output Package metadata and public component discovery helpers.+ * @position Single registry used by audit rosters and component knowledge paths.+ */++const fs = require('node:fs');+const path = require('node:path');++/**+ * Component-bearing packages covered by both the audit roster and component+ * knowledge records.+ *+ * `nested`: components are exported through package and component barrels, and+ * independently public components are identified by their consumer docs.+ * `flat`: public component modules live directly under src and are exported by+ * the package barrel.+ */+const COMPONENT_PACKAGES = Object.freeze([+ {name: 'core', src: 'packages/core/src', layout: 'nested'},+ {name: 'lab', src: 'packages/lab/src', layout: 'nested'},+ {name: 'charts', src: 'packages/charts/src', layout: 'flat'},+ {name: 'richtext', src: 'packages/richtext/src', layout: 'flat'},+ {name: 'vega', src: 'packages/vega/src', layout: 'flat'},+]);++const COMPONENT_PACKAGE_NAMES = Object.freeze(+ COMPONENT_PACKAGES.map(pkg => pkg.name),+);+const COMPONENT_NAME = /^[A-Z][A-Za-z0-9]*$/;++function componentPackage(name) {+ return COMPONENT_PACKAGES.find(pkg => pkg.name === name) ?? null;+}++function resolveLocalModule(fromFile, specifier, sourceRoot) {+ if (!specifier.startsWith('.')) return null;+ const unresolved = path.resolve(path.dirname(fromFile), specifier);+ const relative = path.relative(sourceRoot, unresolved);+ if (relative.startsWith('..') || path.isAbsolute(relative)) return null;++ for (const candidate of [+ unresolved,+ `${unresolved}.tsx`,+ `${unresolved}.ts`,+ path.join(unresolved, 'index.ts'),+ ]) {+ try {+ if (fs.statSync(candidate).isFile()) return candidate;+ } catch {+ // Try the next supported source shape.+ }+ }+ return null;+}++function namedExportItems(list) {+ const items = [];+ for (const rawItem of list.split(',')) {+ const item = rawItem.trim();+ if (!item || item.startsWith('type ')) continue;+ const [sourceName, exportedName = sourceName] = item.split(/\s+as\s+/);+ if (!COMPONENT_NAME.test(exportedName)) continue;+ items.push({sourceName, exportedName});+ }+ return items;+}++/**+ * Resolve every non-type PascalCase export in one public barrel to the TSX+ * module that implements it. This follows local star exports, named exports,+ * aliases, and parent-relative paths without leaving the package source root.+ *+ * @returns {Map<string, string>} public export name -> resolved TSX file+ */+function componentExportsFromBarrel(+ barrelPath,+ sourceRoot,+ state = {cache: new Map(), visiting: new Set()},+) {+ const resolvedBarrel = path.resolve(barrelPath);+ const cached = state.cache.get(resolvedBarrel);+ if (cached) return cached;+ if (state.visiting.has(resolvedBarrel)) return new Map();+ state.visiting.add(resolvedBarrel);++ let barrel;+ try {+ barrel = fs.readFileSync(resolvedBarrel, 'utf8');+ } catch {+ const empty = new Map();+ state.visiting.delete(resolvedBarrel);+ state.cache.set(resolvedBarrel, empty);+ return empty;+ }++ const exports = new Map();+ const starExportPattern = /export\s*\*\s*from\s*['"]([^'"]+)['"]/gm;+ for (const match of barrel.matchAll(starExportPattern)) {+ const target = resolveLocalModule(resolvedBarrel, match[1], sourceRoot);+ if (!target || path.extname(target) === '.tsx') continue;+ for (const [name, implementation] of componentExportsFromBarrel(+ target,+ sourceRoot,+ state,+ )) {+ exports.set(name, implementation);+ }+ }++ const namedExportPattern =+ /export\s*(type\s+)?\{([\s\S]*?)\}\s*from\s*['"]([^'"]+)['"]/gm;+ for (const match of barrel.matchAll(namedExportPattern)) {+ if (match[1]) continue;+ const target = resolveLocalModule(resolvedBarrel, match[3], sourceRoot);+ if (!target) continue;+ const items = namedExportItems(match[2]);+ if (path.extname(target) === '.tsx') {+ for (const {exportedName} of items) exports.set(exportedName, target);+ continue;+ }++ const targetExports = componentExportsFromBarrel(target, sourceRoot, state);+ for (const {sourceName, exportedName} of items) {+ const implementation = targetExports.get(sourceName);+ if (implementation) exports.set(exportedName, implementation);+ }+ }++ state.visiting.delete(resolvedBarrel);+ state.cache.set(resolvedBarrel, exports);+ return exports;+}++/** Public PascalCase component exports from a package source root. */+function exportedComponentNames(sourceDir) {+ return [+ ...componentExportsFromBarrel(+ path.join(sourceDir, 'index.ts'),+ sourceDir,+ ).keys(),+ ].sort();+}++function flatPackageComponentNames(repoRoot, packageConfig) {+ return exportedComponentNames(path.join(repoRoot, packageConfig.src));+}++/** Names current consumer docs identify as independent public components. */+function documentedNestedComponentNames(sourceDir) {+ let entries;+ try {+ entries = fs.readdirSync(sourceDir, {withFileTypes: true});+ } catch {+ return [];+ }++ const names = new Set();+ for (const entry of entries) {+ if (!entry.isDirectory() || !COMPONENT_NAME.test(entry.name)) continue;+ const componentDir = path.join(sourceDir, entry.name);+ for (const file of fs.readdirSync(componentDir, {withFileTypes: true})) {+ if (!file.isFile() || !file.name.endsWith('.doc.mjs')) continue;+ const content = fs.readFileSync(+ path.join(componentDir, file.name),+ 'utf8',+ );+ for (const match of content.matchAll(+ /\bname:\s*['"]([A-Z][A-Za-z0-9]*)['"]/g,+ )) {+ names.add(match[1]);+ }+ }+ }+ return [...names];+}++/**+ * Public component exports that current docs identify as independent components.+ * Export resolution, rather than directory or filename equality, keeps aliases+ * and components implemented in another TSX module while excluding family,+ * hook, context, and utility directory names that are not component exports.+ */+function nestedPackageComponentNames(repoRoot, packageConfig) {+ const sourceDir = path.join(repoRoot, packageConfig.src);+ const exported = new Set(exportedComponentNames(sourceDir));+ return documentedNestedComponentNames(sourceDir)+ .filter(name => exported.has(name))+ .sort();+}++function packageHasPublicComponent(repoRoot, packageName, componentName) {+ const packageConfig = componentPackage(packageName);+ if (!packageConfig) return false;+ const names =+ packageConfig.layout === 'flat'+ ? flatPackageComponentNames(repoRoot, packageConfig)+ : nestedPackageComponentNames(repoRoot, packageConfig);+ return names.includes(componentName);+}++module.exports = {+ COMPONENT_PACKAGES,+ COMPONENT_PACKAGE_NAMES,+ componentExportsFromBarrel,+ componentPackage,+ documentedNestedComponentNames,+ exportedComponentNames,+ flatPackageComponentNames,+ nestedPackageComponentNames,+ packageHasPublicComponent,+};diff --git a/scripts/score-ledger.mjs b/scripts/score-ledger.mjsindex c133e78777..6970e17fa2 100644--- a/scripts/score-ledger.mjs+++ b/scripts/score-ledger.mjs@@ -33,8 +33,15 @@ import fs from 'node:fs';import os from 'node:os';import path from 'node:path';import {execFileSync} from 'node:child_process';+import {createRequire} from 'node:module';import {fileURLToPath} from 'node:url';+const require = createRequire(import.meta.url);+const {+ COMPONENT_PACKAGES,+ flatPackageComponentNames,+ nestedPackageComponentNames,+} = require('./component-packages.cjs');const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');/** The one stored form of the ledger, at the root of the wiki repo. */@@ -192,9 +199,6 @@ export const NON_COMPONENT_DIRS = Object.freeze(/** A file that renders: PascalCase `.tsx`, not a test, story, doc or perf file. */const RENDERING_FILE = /^[A-Z][A-Za-z0-9]*\.tsx$/;-/** A documented component in a flat package: PascalCase `<Name>.doc.mjs`. */-const FLAT_DOC_FILE = /^([A-Z][A-Za-z0-9]*)\.doc\.mjs$/;-/*** Packages the ledger covers, with the src dir the predicate sweeps and how* that src is laid out.@@ -202,20 +206,13 @@ const FLAT_DOC_FILE = /^([A-Z][A-Za-z0-9]*)\.doc\.mjs$/;* - `nested` (core, lab): one directory per component, `<Name>/<Name>.tsx`.* The directory is the unit; `isComponentDirectory` filters out the* styles-only and context-only ones.- * - `flat` (richtext, promoted out of lab so it can be canaried on its own):- * `<Name>.tsx` files at the src root alongside internal helpers, so there- * is no directory to key on and the `.doc.mjs` is the component boundary.+ * - `flat` (charts, richtext, vega): public component modules live directly+ * under `src/` and are identified from matching named exports in `src/index.ts`.*- * A component graduating from lab into its own package (richtext did) must be- * registered here or it silently drops out of the ledger's denominator — the- * roster reads only these packages, and a score recorded for it in the wiki- * has no row to attach to.+ * Add a component-bearing package to `scripts/component-packages.cjs`; the audit+ * roster and component-spec path validation consume that one registry.*/-export const LEDGER_PACKAGES = Object.freeze([- {name: 'core', src: 'packages/core/src', layout: 'nested'},- {name: 'lab', src: 'packages/lab/src', layout: 'nested'},- {name: 'richtext', src: 'packages/richtext/src', layout: 'flat'},-]);+export const LEDGER_PACKAGES = COMPONENT_PACKAGES;/** The covered package names, for human-facing CLI messages. */const LEDGER_PACKAGE_NAMES = LEDGER_PACKAGES.map(p => p.name);@@ -258,35 +255,19 @@ export function isComponentDirectory(srcDir, dirName) {}/**- * The component names in a flat package src (richtext), where `<Name>.tsx`- * files sit at the root alongside internal helpers rather than in a directory- * each. A `.doc.mjs` is the boundary here: the root also holds sub-parts and- * plugins (`RichTextEditorToolbar.tsx`, `RichTextEditorAutoLinkPlugin.tsx`)- * that render but are not audited as components on their own, and the doc file- * is what distinguishes the public component from them — the same unit the- * docsite and the wiki ledger already record.+ * Public component names in a flat package. Matching named exports from+ * `src/index.ts` define the boundary; private rendering helpers and TSX context+ * modules that export only hooks stay out.** @param {string} srcDir absolute path to `packages/<pkg>/src`- * @returns {string[]} component names, e.g. `['RichTextEditor']`+ * @param {string} [repoRoot]+ * @returns {string[]} public component names*/-export function flatPackageComponents(srcDir) {- let entries;- try {- entries = fs.readdirSync(srcDir, {withFileTypes: true});- } catch {- return [];- }- const names = [];- for (const entry of entries) {- if (!entry.isFile()) continue;- const match = FLAT_DOC_FILE.exec(entry.name);- if (!match) continue;- // A doc without the component it documents is a dangling file, not a row.- if (fs.existsSync(path.join(srcDir, `${match[1]}.tsx`))) {- names.push(match[1]);- }- }- return names;+export function flatPackageComponents(srcDir, repoRoot = ROOT) {+ const packageConfig = COMPONENT_PACKAGES.find(+ pkg => path.resolve(repoRoot, pkg.src) === path.resolve(srcDir),+ );+ return packageConfig ? flatPackageComponentNames(repoRoot, packageConfig) : [];}/**@@ -299,25 +280,19 @@ export function listComponents(repoRoot = ROOT) {const out = [];for (const pkg of LEDGER_PACKAGES) {const srcDir = path.join(repoRoot, pkg.src);- if (pkg.layout === 'flat') {- for (const component of flatPackageComponents(srcDir)) {- out.push({component, package: pkg.name});- }- continue;- }- let entries;- try {- entries = fs.readdirSync(srcDir, {withFileTypes: true});- } catch {- continue;- }- for (const entry of entries) {- if (!entry.isDirectory()) continue;- if (!isComponentDirectory(srcDir, entry.name)) continue;- out.push({component: entry.name, package: pkg.name});+ const components =+ pkg.layout === 'flat'+ ? flatPackageComponents(srcDir, repoRoot)+ : nestedPackageComponentNames(repoRoot, pkg);+ for (const component of components) {+ out.push({component, package: pkg.name});}}- return out.sort((a, b) => a.component.localeCompare(b.component));+ return out.sort(+ (a, b) =>+ a.component.localeCompare(b.component) ||+ a.package.localeCompare(b.package),+ );}// ---------------------------------------------------------------------------diff --git a/scripts/score-ledger.test.mjs b/scripts/score-ledger.test.mjsindex 8b646c2e81..ee01b88fc6 100644--- a/scripts/score-ledger.test.mjs+++ b/scripts/score-ledger.test.mjs@@ -195,30 +195,33 @@ describe('the ratchet', () => {});describe('a component is a package AND a name', () => {- // `Chat` ships in both core and lab. A name-keyed ledger would ratchet one- // against the other, which is worse than not measuring either.+ const duplicateRoster = [+ {component: 'Shared', package: 'core'},+ {component: 'Shared', package: 'lab'},+ ];+it('resolves a name that exists in two packages to both components', () => {- const matches = resolveName('Chat', listComponents(REPO_ROOT));+ const matches = resolveName('Shared', duplicateRoster);expect(matches.map(m => m.package).sort()).toEqual(['core', 'lab']);});it('keeps the two apart in the ratchet — a lab score cannot fail a core PR', () => {const base = {components: [- entry({component: 'Chat', package: 'core', score: 80, grade: 'B'}),- entry({component: 'Chat', package: 'lab', score: 80, grade: 'B'}),+ entry({component: 'Shared', package: 'core', score: 80, grade: 'B'}),+ entry({component: 'Shared', package: 'lab', score: 80, grade: 'B'}),],};const head = {components: [- entry({component: 'Chat', package: 'core', score: 80, grade: 'B'}),- entry({component: 'Chat', package: 'lab', score: 40, grade: 'F'}),+ entry({component: 'Shared', package: 'core', score: 80, grade: 'B'}),+ entry({component: 'Shared', package: 'lab', score: 40, grade: 'F'}),],};- const {results} = runRatchet(['Chat'], base, head);- expect(results.map(r => r.component).sort()).toEqual(['core/Chat', 'lab/Chat']);- expect(results.find(r => r.component === 'core/Chat').verdict).toBe('pass');- expect(results.find(r => r.component === 'lab/Chat').verdict).toBe('fail');+ const {results} = runRatchet(['Shared'], base, head, duplicateRoster);+ expect(results.map(r => r.component).sort()).toEqual(['core/Shared', 'lab/Shared']);+ expect(results.find(r => r.component === 'core/Shared').verdict).toBe('pass');+ expect(results.find(r => r.component === 'lab/Shared').verdict).toBe('fail');});it('gives each roster row a package-qualified id', () => {@@ -327,37 +330,61 @@ describe('the canonical component predicate', () => {const names = all.map(c => c.component);expect(names).toContain('Button');expect(names).toContain('Stepper');+ expect(names).toContain('ChatComposerTokenElement');+ expect(names).toContain('ContextMenuItem');+ expect(names).toContain('TransferListSelector');+ expect(names).toContain('TourStep');expect(names).not.toContain('hooks');expect(names).not.toContain('NavItem');+ expect(names).not.toContain('Chat');+ expect(names).not.toContain('Indicator');+ expect(names).not.toContain('Layer');+ expect(names).not.toContain('NavMenu');+ expect(names).not.toContain('Resizable');+ expect(names).not.toContain('ContextMenuItemProps');expect([...names].sort((a, b) => a.localeCompare(b))).toEqual(names);expect(new Set(all.map(c => c.package))).toEqual(- new Set(['core', 'lab', 'richtext']),+ new Set(['charts', 'core', 'lab', 'richtext', 'vega']),);});- it('covers flat packages by their .doc.mjs, not a per-component dir', () => {- // richtext was promoted out of lab into its own package with a flat src- // (`RichTextEditor.tsx` at the root, no directory per component). It must- // still land in the roster or a score recorded for it has no row.- const all = listComponents(REPO_ROOT);- const richtext = all.filter(c => c.package === 'richtext');- expect(richtext).toEqual([{component: 'RichTextEditor', package: 'richtext'}]);+ it('covers every public component in flat component packages', () => {+ const byPackage = new Map();+ for (const item of listComponents(REPO_ROOT)) {+ const names = byPackage.get(item.package) ?? [];+ names.push(item.component);+ byPackage.set(item.package, names);+ }+ expect(byPackage.get('charts')).toEqual([+ 'Chart',+ 'ChartAxis',+ 'ChartGrid',+ 'ChartLegend',+ 'ChartSwatch',+ 'ChartTooltip',+ ]);+ expect(byPackage.get('richtext')).toEqual([+ 'RichTextEditor',+ 'RichTextEditorAutoLinkPlugin',+ 'RichTextEditorToolbar',+ 'RichTextView',+ ]);+ expect(byPackage.get('vega')).toEqual(['VegaChart']);});});describe('the flat-package component predicate', () => {const richtextSrc = path.join(REPO_ROOT, 'packages/richtext/src');- it('keeps the documented component', () => {- expect(flatPackageComponents(richtextSrc)).toContain('RichTextEditor');- });-- it('drops undocumented sub-parts and helpers that still render', () => {- // These render but carry no `.doc.mjs`, so they are not audited rows.+ it('keeps public exported components and drops private helpers', () => {const names = flatPackageComponents(richtextSrc);- expect(names).not.toContain('RichTextView');- expect(names).not.toContain('RichTextEditorToolbar');- expect(names).not.toContain('RichTextEditorAutoLinkPlugin');+ expect(names).toEqual([+ 'RichTextEditor',+ 'RichTextEditorAutoLinkPlugin',+ 'RichTextEditorToolbar',+ 'RichTextView',+ ]);+ expect(names).not.toContain('LexicalErrorBoundary');});it('returns nothing for a src dir that does not exist', () => {