An open source design system that's fully customizable and agent ready
TypeScript
test(cli): the swizzle proof gates component and swizzle changes (AST-110 FR7) (#10651)
Cindy Zhang15c678835014
diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.ymlindex c01658f095..fd07b88d12 100644--- a/.github/workflows/deploy.yml+++ b/.github/workflows/deploy.yml@@ -202,13 +202,20 @@ jobs:permissions:contents: readsteps:+ # Two commits: the swizzle proof diffs main's squash-merged commit+ # against its parent to prove only the copies that change affects+ # (spec:AST-110 FR7).- uses: actions/checkout@v7with:ref: ${{ needs.main-commit.outputs.sha }}+ fetch-depth: 2- uses: ./.github/actions/setup- run: pnpm test:node --shard=${{ matrix.shard }}/${{ strategy.job-total }}+ env:+ # A release re-check proves every swizzle target (spec:AST-110 FR7).+ SWIZZLE_PROOF_ALL: ${{ inputs.recheck && '1' || '' }}# The typecheck mirroring the PR `build` job in ci.yml. ci.yml only runs# on pull_request/merge_group, so a typecheck error can land on main (itsdiff --git a/packages/cli/test/swizzle-proof/proof.mjs b/packages/cli/test/swizzle-proof/proof.mjsnew file mode 100644index 0000000000..c55d0f3a2a--- /dev/null+++ b/packages/cli/test/swizzle-proof/proof.mjs@@ -0,0 +1,892 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file proof.mjs+ * @input The repository's workspace packages and a change (changed paths)+ * @output The swizzle proof (spec:AST-110 FR7): for each target it ejects+ * the copy into a clean project, checks its imports and files,+ * type-checks it, bundles it with the StyleX compiler, and renders it once+ * on the server. It also decides which targets a change affects.+ * @position Shared by the swizzle proof tests; no Vitest import+ */++import {execFileSync} from 'node:child_process';+import fs from 'node:fs';+import {createRequire} from 'node:module';+import path from 'node:path';+import {fileURLToPath, pathToFileURL} from 'node:url';++import {+ moduleExportOrigins,+ resolveLocalModule,+} from '../../foundation/discovery/module-exports.mjs';+import {sourceExportTarget} from '../../foundation/discovery/package-exports.mjs';++export const REPO = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '../../../..',+);+const requireFromRepo = createRequire(path.join(REPO, 'package.json'));++/** The workspace packages swizzle copies components from. */+export const COMPONENT_PACKAGES = ['core', 'lab', 'charts', 'richtext', 'vega'];++/**+ * A change to one of these paths can change every copy, so it proves every+ * target: the StyleX build, the proof itself, and a component package's+ * manifest (its exports route the copy's imports). The swizzle copy and the+ * CLI modules it reads count too ({@link swizzleModules}).+ */+const TOOLCHAIN = [+ /^packages\/build\/src\//,+ /^packages\/cli\/test\/swizzle-proof\//,+ /^packages\/(?:core|lab|charts|richtext|vega)\/package\.json$/,+];+/** A dependency whose change can change every copy's build. */+const TOOLCHAIN_DEPENDENCY =+ /(?:^|[\s'"/])(?:vite|@vitejs\/plugin-react|@stylexjs\/[\w-]+|typescript|react|react-dom|@babel\/[\w-]+|@types\/react(?:-dom)?)(?:@|['"]\s*:)/;++/**+ * The CLI modules `astryx swizzle` runs: the swizzle API and every module it+ * imports, by relative path, repository-relative.+ */+function swizzleModules() {+ const start = path.join(REPO, 'packages/cli/api/swizzle');+ const queue = fs+ .readdirSync(start, {recursive: true})+ .map(String)+ .filter(f => /\.mjs$/.test(f) && !/\.test\.mjs$/.test(f))+ .map(f => path.join(start, f));+ const seen = new Set();+ while (queue.length > 0) {+ const file = queue.shift();+ if (seen.has(file) || !fs.existsSync(file)) continue;+ seen.add(file);+ const code = fs.readFileSync(file, 'utf8');+ for (const [, spec] of code.matchAll(+ /(?:from|import)\s*\(?\s*['"](\.[^'"]+)['"]/g,+ )) {+ queue.push(path.resolve(path.dirname(file), spec));+ }+ }+ return new Set([...seen].map(f => path.relative(REPO, f)));+}++/**+ * The first changed path that can change every copy, or undefined. The+ * lockfile and the root manifest count only when a changed line names a+ * build dependency.+ * @param {string[]} changed+ * @param {string} base+ */+export function toolchainChange(changed, base) {+ const swizzle = swizzleModules();+ return changed.find(file => {+ if (swizzle.has(file) || TOOLCHAIN.some(re => re.test(file))) return true;+ if (file !== 'pnpm-lock.yaml' && file !== 'package.json') return false;+ try {+ const head = process.env.SWIZZLE_PROOF_HEAD;+ const diff = execFileSync(+ 'git',+ ['diff', '-U0', base, ...(head ? [head] : []), '--', file],+ {cwd: REPO, encoding: 'utf8', maxBuffer: 256e6},+ );+ return diff+ .split('\n')+ .some(+ line => /^[-+][^-+]/.test(line) && TOOLCHAIN_DEPENDENCY.test(line),+ );+ } catch {+ // A diff git cannot read proves every target.+ return true;+ }+ });+}++const SOURCE_FILE = /\.(?:ts|tsx|mts|js|mjs|jsx)$/;+const NOT_SHIPPED =+ /\.(?:test|spec|stories|story|doc|bench)\.[cm]?[jt]sx?$|(?:^|\/)__(?:tests|fixtures|mocks)__\//;++/** Every workspace package by name, with its folder and manifest. */+export function workspacePackages() {+ /** @type {Map<string, {dir: string, manifest: any}>} */+ const found = new Map();+ for (const parent of ['packages', 'packages/themes']) {+ const root = path.join(REPO, parent);+ for (const entry of fs.readdirSync(root, {withFileTypes: true})) {+ const file = path.join(root, entry.name, 'package.json');+ if (!entry.isDirectory() || !fs.existsSync(file)) continue;+ const manifest = JSON.parse(fs.readFileSync(file, 'utf8'));+ if (manifest.name) {+ found.set(manifest.name, {dir: path.dirname(file), manifest});+ }+ }+ }+ return found;+}++/**+ * The paths a change touches, relative to the repository, or null when git+ * cannot tell. On a pull request's merge commit the base is its first+ * parent. A pull request run checks out that parent, so null there means+ * git failed, and the slice proves every target.+ * @param {string} [base]+ * @returns {string[]|null}+ */+export function changedPaths(+ base = process.env.SWIZZLE_PROOF_BASE ?? 'HEAD^1',+) {+ // A replayed change names its paths directly.+ if (process.env.SWIZZLE_PROOF_CHANGED) {+ return process.env.SWIZZLE_PROOF_CHANGED.split(',').filter(Boolean);+ }+ try {+ const head = process.env.SWIZZLE_PROOF_HEAD;+ const out = execFileSync(+ 'git',+ ['diff', '--name-only', base, ...(head ? [head] : [])],+ {+ cwd: REPO,+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'ignore'],+ },+ );+ return out.split('\n').filter(Boolean);+ } catch {+ return null;+ }+}++/**+ * A clean product project: every workspace package and every npm package a+ * component package declares are installed, as a product that follows the+ * receipt's install line would have them.+ * @param {string} dir+ */+export function createProject(dir) {+ fs.rmSync(dir, {recursive: true, force: true});+ const modules = path.join(dir, 'node_modules');+ fs.mkdirSync(modules, {recursive: true});+ const link = (name, target) => {+ const at = path.join(modules, name);+ if (fs.existsSync(at) || !fs.existsSync(target)) return;+ fs.mkdirSync(path.dirname(at), {recursive: true});+ fs.symlinkSync(fs.realpathSync(target), at, 'junction');+ };+ const packages = workspacePackages();+ for (const [name, {dir: packageDir}] of packages) link(name, packageDir);+ for (const short of COMPONENT_PACKAGES) {+ const {dir: packageDir, manifest} = packages.get(`@astryxdesign/${short}`);+ const names = Object.keys({+ ...manifest.dependencies,+ ...manifest.optionalDependencies,+ ...manifest.peerDependencies,+ });+ for (const name of names) {+ if (name.startsWith('@astryxdesign/')) continue;+ link(name, path.join(packageDir, 'node_modules', name));+ link(name, path.join(REPO, 'node_modules', name));+ // A package without its own types needs its DefinitelyTyped package.+ const types = `@types/${name.replace(/^@([^/]+)\//, '$1__')}`;+ link(types, path.join(packageDir, 'node_modules', types));+ link(types, path.join(REPO, 'node_modules', types));+ }+ }+ for (const name of [+ 'react',+ 'react-dom',+ '@types/react',+ '@types/react-dom',+ '@stylexjs/stylex',+ ]) {+ link(name, path.join(REPO, 'node_modules', name));+ }+ // The product depends on every component package, so the CLI finds the+ // integration packages to list and copy from.+ const dependencies = Object.fromEntries(+ [...packages].map(([name, {manifest}]) => [name, manifest.version]),+ );+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({+ name: 'swizzle-proof',+ private: true,+ type: 'module',+ dependencies,+ }),+ );+}++/** Imports the CLI's API modules from the repository's own source. */+async function cliApi() {+ const api = path.join(REPO, 'packages/cli/api');+ const {swizzle} = await import(+ pathToFileURL(path.join(api, 'swizzle/swizzle.mjs')).href+ );+ const {component} = await import(+ pathToFileURL(path.join(api, 'component/component.mjs')).href+ );+ return {swizzle, component};+}++/**+ * Every target swizzle can copy: Core's components as `swizzle --list` offers+ * them, and each integration package's components (copied with `--package`).+ * @param {string} project+ * @returns {Promise<Array<{name: string, pkg: string, key: string}>>}+ */+export async function listTargets(project) {+ const {swizzle, component} = await cliApi();+ /** @type {Array<{name: string, pkg: string}>} */+ const list = (await swizzle(undefined, {cwd: project, list: true})).data.map(+ name => ({name, pkg: '@astryxdesign/core'}),+ );+ const groups = (await component(undefined, {cwd: project, list: true})).data+ .components;+ for (const entries of Object.values(groups)) {+ for (const entry of entries) {+ if (entry.package && entry.package !== '@astryxdesign/core') {+ list.push({name: entry.name, pkg: entry.package});+ }+ }+ }+ return list.map(t => ({...t, key: keyOf(t)}));+}++/** @param {{name: string, pkg: string}} t */+export function keyOf(t) {+ return `${t.pkg.replace('@astryxdesign/', '')}__${t.name}`;+}++/**+ * Ejects each target into the project; records each copy's folder and files.+ * @param {Array<{name: string, pkg: string, key: string}>} targets+ * @param {string} project+ * @param {Map<string, {dir: string, outBase: string, files: string[]}>} copies+ * @param {(key: string, step: string, error: unknown) => void} fail+ */+async function eject(targets, project, copies, fail) {+ const {swizzle} = await cliApi();+ for (const t of targets) {+ const out = path.join(+ 'components',+ t.pkg.replace('@astryxdesign/', ''),+ t.name,+ );+ try {+ const res = await swizzle(t.name, {+ cwd: project,+ output: out,+ overwrite: true,+ ...(t.pkg === '@astryxdesign/core' ? {} : {package: t.pkg}),+ });+ const dir = path.join(project, out, res.data.component);+ copies.set(t.key, {+ dir,+ outBase: path.join(project, out),+ files: res.data.files.map(f => path.resolve(dir, f)),+ });+ } catch (error) {+ fail(t.key, 'eject', error.message ?? error);+ }+ }+}++/**+ * The source folder a copy's component files come from: the one folder in+ * the package's source that holds every one of them, or null.+ * @param {{name: string}} t+ * @param {{dir: string, files: string[]}} copy+ * @param {string} src+ */+function componentSourceDir(t, copy, src) {+ const own = copy.files+ .filter(f => f.startsWith(copy.dir + path.sep))+ .map(f => path.relative(copy.dir, f));+ if (own.length === 0) return null;+ const all = fs.readdirSync(src, {recursive: true}).map(String);+ const candidates = all+ .filter(f => f === own[0] || f.endsWith(path.sep + own[0]))+ .map(f => path.join(src, f.slice(0, f.length - own[0].length)));+ const matches = candidates.filter(dir =>+ own.every(r => fs.existsSync(path.join(dir, r))),+ );+ return matches.length === 1 ? path.resolve(matches[0]) : null;+}++/**+ * A module and every module it imports by relative path, transitively: what+ * the copy's bundle runs when it imports one of the module's names.+ * @param {string} file+ * @param {Map<string, Set<string>>} closures cache, by module+ */+function localClosure(file, closures) {+ const cached = closures.get(file);+ if (cached) return cached;+ /** @type {Set<string>} */+ const seen = new Set();+ const queue = [file];+ while (queue.length > 0) {+ const next = queue.shift();+ if (seen.has(next)) continue;+ seen.add(next);+ let code;+ try {+ code = fs.readFileSync(next, 'utf8');+ } catch {+ continue;+ }+ for (const [, spec] of code.matchAll(+ /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+)['"](\.[^'"]+)['"]/g,+ )) {+ const resolved = resolveLocalModule(spec, next);+ if (resolved && !seen.has(resolved)) queue.push(resolved);+ }+ }+ closures.set(file, seen);+ return seen;+}++/**+ * The source files a copy depends on: each module it carries, the entry+ * module of each package export it imports from, and the module that+ * defines each public name it imports with every module that one imports. Null when the copy's component folder+ * matches no single source folder.+ * @param {{name: string, pkg: string}} t+ * @param {{outBase: string, files: string[]}} copy+ * @param {Map<string, {dir: string, manifest: any}>} packages+ * @param {Map<string, Map<string, {file: string}>>} memo+ */+export function sourcesOf(t, copy, packages, memo, closures = new Map()) {+ const srcOf = name => path.join(packages.get(name).dir, 'src');+ const own = t.pkg.replace('@astryxdesign/', '');+ const componentSource = componentSourceDir(t, copy, srcOf(t.pkg));+ // A copy whose component folder cannot be matched to one source folder+ // depends on everything (fail closed).+ if (componentSource == null) return null;+ /** @type {Set<string>} */+ const sources = new Set();+ const named =+ /import\s+(?:type\s+)?(\{[^}]*\}|\*\s+as\s+\w+|\w+)?\s*(?:,\s*(\{[^}]*\}))?\s*from\s*['"](@astryxdesign\/[^'"]+)['"]/g;+ for (const file of copy.files) {+ // Swizzle writes the component's own files under its output folder,+ // whatever folder they come from; helpers keep their path in the+ // package's source, and a module from another package sits under a+ // folder named after that package.+ if (file.startsWith(copy.dir + path.sep)) {+ sources.add(path.join(componentSource, path.relative(copy.dir, file)));+ } else {+ const rel = path.relative(copy.outBase, file);+ const [first, ...rest] = rel.split(path.sep);+ const other = COMPONENT_PACKAGES.includes(first) && first !== own;+ sources.add(+ other+ ? path.join(srcOf(`@astryxdesign/${first}`), ...rest)+ : path.join(srcOf(t.pkg), rel),+ );+ }+ if (!/\.tsx?$/.test(file)) continue;+ for (const [, head, tail, spec] of fs+ .readFileSync(file, 'utf8')+ .matchAll(named)) {+ const [, name, ...sub] = spec.split('/');+ const owner = packages.get(`@astryxdesign/${name}`);+ if (!owner) continue;+ const target = sourceExportTarget(+ owner.manifest,+ owner.dir,+ sub.length ? `./${sub.join('/')}` : '.',+ );+ if (!target) continue;+ // The export's entry module routes the import as the manifest does.+ sources.add(target);+ const list = [head, tail].filter(x => x && x.startsWith('{'));+ if (list.length === 0) continue;+ if (!memo.has(target)) {+ let origins;+ try {+ origins = moduleExportOrigins(target, {types: true});+ } catch {+ origins = new Map();+ }+ memo.set(target, origins);+ }+ for (const entry of list.join(',').replace(/[{}]/g, '').split(',')) {+ const imported = entry+ .trim()+ .replace(/^type\s+/, '')+ .split(/\s+as\s+/)[0];+ if (!imported) continue;+ const origin = memo.get(target).get(imported)?.file ?? target;+ for (const file of localClosure(origin, closures)) sources.add(file);+ }+ }+ }+ return sources;+}++/**+ * Which targets a run proves: none, the affected ones, or all. When git+ * cannot read the change, a checkout without a parent commit proves none+ * (there is no base to diff), and any other run proves every target (fail+ * closed).+ * @param {{changed: string[]|null, toolchain: string|undefined, relevant: string[], hasParent: boolean, all?: boolean}} change+ * @returns {{mode: 'none'|'affected'|'all', reason: string}}+ */+export function proofScope({+ changed,+ toolchain,+ relevant,+ hasParent,+ all = false,+}) {+ if (all) return {mode: 'all', reason: 'every target was asked for'};+ if (changed == null) {+ if (!hasParent) {+ return {+ mode: 'none',+ reason:+ 'the checkout has no parent commit to diff against, so no target runs',+ };+ }+ return {+ mode: 'all',+ reason: 'the change could not be read, so every target runs',+ };+ }+ if (toolchain)+ return {mode: 'all', reason: `${toolchain} can change every copy`};+ if (relevant.length === 0) {+ return {+ mode: 'none',+ reason: 'no component source or toolchain path changed',+ };+ }+ return {mode: 'affected', reason: ''};+}++/** Whether the checkout holds the parent of its commit. */+function hasParentCommit() {+ try {+ execFileSync('git', ['rev-parse', '--verify', '--quiet', 'HEAD^1'], {+ cwd: REPO,+ stdio: 'ignore',+ });+ return true;+ } catch {+ return false;+ }+}++/**+ * Runs one slice of the proof: the targets at `index` of every `count`, in+ * the scope {@link proofScope} chooses. In the affected scope the slice+ * proves the targets whose copy depends on a changed source file.+ * @param {{index: number, count: number, samples: Record<string, Function>, notRendered: Record<string, string>, project: string, all?: boolean}} options+ */+export async function runSlice({+ index,+ count,+ samples,+ notRendered,+ project,+ all = false,+}) {+ const start = Date.now();+ const base = process.env.SWIZZLE_PROOF_BASE ?? 'HEAD^1';+ const changed = all ? null : changedPaths(base);+ const toolchain = changed && toolchainChange(changed, base);+ const relevant = (changed ?? []).filter(+ file =>+ COMPONENT_PACKAGES.some(short =>+ file.startsWith(`packages/${short}/src/`),+ ) && !NOT_SHIPPED.test(file),+ );+ const scope = proofScope({+ changed,+ toolchain,+ relevant,+ hasParent: hasParentCommit(),+ all,+ });+ if (scope.mode === 'none') {+ return {+ offered: null,+ affected: 0,+ reason: scope.reason,+ results: [],+ timings: {},+ totalMs: Date.now() - start,+ };+ }+ createProject(project);+ const timings = {};+ const listStart = Date.now();+ const slice = (await listTargets(project)).filter(+ (_, i) => i % count === index,+ );+ timings.list = Date.now() - listStart;+ /** @type {Map<string, any>} */+ const ejected = new Map();+ const failures = new Map();+ const ejectStart = Date.now();+ await eject(slice, project, ejected, (key, step, error) => {+ if (!failures.has(key))+ failures.set(key, {step, error: String(error).slice(0, 400)});+ });+ timings.eject = Date.now() - ejectStart;+ let affected = slice;+ let reason = scope.mode === 'all' ? scope.reason : '';+ if (!reason) {+ const packages = workspacePackages();+ const memo = new Map();+ const closures = new Map();+ const changedFiles = new Set(relevant.map(file => path.join(REPO, file)));+ const affectStart = Date.now();+ affected = slice.filter(t => {+ // A target that did not eject is proven, so its failure shows.+ if (!ejected.has(t.key)) return true;+ const sources = sourcesOf(+ t,+ ejected.get(t.key),+ packages,+ memo,+ closures,+ );+ if (sources == null) return true;+ for (const file of sources) {+ // A source that does not exist means the mapping is wrong: prove it.+ if (changedFiles.has(file) || !fs.existsSync(file)) return true;+ }+ return false;+ });+ timings.affected = Date.now() - affectStart;+ reason = `${relevant.length} changed source file(s); ${affected.length} of ${slice.length} target(s) in this slice depend on them`;+ }+ const ejectedAffected = affected.filter(t => ejected.has(t.key));+ const proof = ejectedAffected.length+ ? await prove(ejectedAffected, {project, samples, notRendered, ejected})+ : {results: [], timings: {}};+ for (const t of affected) {+ if (!ejected.has(t.key))+ proof.results.push({key: t.key, failure: failures.get(t.key)});+ }+ return {+ offered: slice.length,+ affected: affected.length,+ reason,+ results: proof.results,+ timings: {...timings, ...proof.timings},+ totalMs: Date.now() - start,+ };+}++/**+ * Proves each target. Each step's failure is recorded on the target, and a+ * target that fails a step skips the later ones.+ * @param {Array<{name: string, pkg: string, key: string}>} targets+ * @param {{project: string, samples: Record<string, Function>}} options+ */+export async function prove(+ targets,+ {project, samples, notRendered = {}, ejected},+) {+ const timings = {};+ const time = async (step, run) => {+ const start = Date.now();+ await run();+ timings[step] = Date.now() - start;+ };+ /** @type {Map<string, {key: string, failure?: {step: string, error: string}}>} */+ const results = new Map(targets.map(t => [t.key, {key: t.key}]));+ const fail = (key, step, error) => {+ const result = results.get(key);+ if (!result.failure)+ result.failure = {step, error: String(error).slice(0, 400)};+ };+ const alive = () => targets.filter(t => !results.get(t.key).failure);+ const renderable = () => alive().filter(t => !notRendered[t.key]);++ /** @type {Map<string, {dir: string, files: string[]}>} */+ const copies = ejected ?? new Map();+ if (!ejected)+ await time('eject', () => eject(targets, project, copies, fail));++ await time('imports', async () => {+ const internal = /['"](@astryxdesign\/([^/'"]+)\/internal\/[^'"]+)['"]/g;+ for (const t of alive()) {+ for (const file of copies.get(t.key).files) {+ const rel = path.relative(project, file);+ if (NOT_SHIPPED.test(rel)) {+ fail(t.key, 'files', `${rel} is not shipped code`);+ continue;+ }+ if (!SOURCE_FILE.test(file)) continue;+ for (const [, spec, pkg] of fs+ .readFileSync(file, 'utf8')+ .matchAll(internal)) {+ // A StyleX module another package exports under ./internal/ keeps+ // its import (spec:AST-110 FR1).+ if (`@astryxdesign/${pkg}` === t.pkg || !spec.endsWith('.stylex')) {+ fail(t.key, 'imports', `${rel} imports ${spec}`);+ }+ }+ }+ }+ });++ await time('typecheck', async () => {+ const ts = requireFromRepo('typescript');+ const files = alive().flatMap(t =>+ copies.get(t.key).files.filter(f => /\.tsx?$/.test(f)),+ );+ const program = ts.createProgram(files, {+ target: ts.ScriptTarget.ES2022,+ module: ts.ModuleKind.ESNext,+ moduleResolution: ts.ModuleResolutionKind.Bundler,+ customConditions: ['source'],+ jsx: ts.JsxEmit.ReactJSX,+ strict: true,+ skipLibCheck: true,+ noEmit: true,+ types: [],+ lib: ['lib.es2023.d.ts', 'lib.dom.d.ts', 'lib.dom.iterable.d.ts'],+ resolveJsonModule: true,+ isolatedModules: true,+ });+ const owner = new Map();+ for (const t of alive()) {+ for (const f of copies.get(t.key).files)+ owner.set(path.resolve(f), t.key);+ }+ for (const d of ts.getPreEmitDiagnostics(program)) {+ const file = d.file && path.resolve(d.file.fileName);+ const key = file && owner.get(file);+ if (key) {+ fail(+ key,+ 'typecheck',+ `${path.relative(project, file)}: TS${d.code} ${ts.flattenDiagnosticMessageText(d.messageText, ' ')}`,+ );+ }+ }+ });++ await time('entries', async () => {+ const entries = path.join(project, 'entries');+ fs.rmSync(entries, {recursive: true, force: true});+ fs.mkdirSync(entries, {recursive: true});+ const samplesFile = path.join(entries, 'samples.mjs');+ fs.writeFileSync(+ samplesFile,+ `export {samples} from ${JSON.stringify(pathToFileURL(path.join(REPO, 'packages/cli/test/swizzle-proof/samples.mjs')).href)};\n`,+ );+ const packages = workspacePackages();+ for (const t of alive()) {+ if (notRendered[t.key]) continue;+ const defaults = await playgroundDefaults(packages, t);+ const entry = entryFileOf(copies.get(t.key).dir, t.name);+ if (!entry) {+ fail(t.key, 'render', 'the copy has no entry module');+ continue;+ }+ fs.writeFileSync(+ path.join(entries, `${t.key}.tsx`),+ [+ `import * as React from 'react';`,+ `import {renderToString} from 'react-dom/server';`,+ `import * as Core from '@astryxdesign/core';`,+ `import * as Pkg from '${t.pkg}';`,+ `import * as Copy from ${JSON.stringify(+ path+ .relative(entries, entry)+ .replace(/\.tsx?$/, '')+ .replace(/^(?!\.)/, './'),+ )};`,+ `import {samples} from './samples.mjs';`,+ `const C = Copy[${JSON.stringify(t.name)}];`,+ `const defaults = ${JSON.stringify(defaults)};`,+ // Playground defaults name elements as {__element, props, children}.+ `function revive(v) {`,+ ` if (Array.isArray(v)) return v.map(revive);`,+ ` if (v && typeof v === 'object') {`,+ ` if (v.__element) {`,+ ` const kids = v.children == null ? [] : [].concat(v.children).map(revive);`,+ ` return React.createElement(Copy[v.__element] ?? Pkg[v.__element] ?? Core[v.__element] ?? v.__element, revive(v.props ?? {}), ...kids);`,+ ` }`,+ ` return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, revive(x)]));`,+ ` }`,+ ` return v;`,+ `}`,+ `export function render() {`,+ ` const make = samples[${JSON.stringify(t.key)}];`,+ ` if (!make && C == null) throw new Error('the copy exports no ${t.name}');`,+ ` return renderToString(make ? make({C, mod: Copy, React, Core, Pkg}) : React.createElement(C, revive(defaults)));`,+ `}`,+ '',+ ].join('\n'),+ );+ }+ });++ const vite = await import(+ pathToFileURL(requireFromRepo.resolve('vite')).href+ );+ const {default: react} = await import(+ pathToFileURL(requireFromRepo.resolve('@vitejs/plugin-react')).href+ );+ const stylexBabel = path.join(REPO, 'packages/build/src/babel.js');+ const plugins = () => [+ react({+ babel: {+ plugins: [+ [+ stylexBabel,+ {+ dev: false,+ runtimeInjection: false,+ treeshakeCompensation: true,+ enableInlinedConditionalMerge: true,+ unstable_moduleResolution: {type: 'commonJS', rootDir: project},+ },+ ],+ ],+ },+ }),+ ];+ const resolve = {+ conditions: ['source', 'module', 'browser', 'default'],+ preserveSymlinks: false,+ };+ /** Builds the targets' entries together, splitting a failing batch until each failure is one target's. */+ const batch = async (step, keys, build) => {+ const run = async list => {+ try {+ await build(list);+ return true;+ } catch (error) {+ if (list.length === 1) {+ fail(+ list[0],+ step,+ String(error.message ?? error)+ .split('\n')+ .slice(0, 3)+ .join(' '),+ );+ return false;+ }+ const mid = Math.ceil(list.length / 2);+ await run(list.slice(0, mid));+ await run(list.slice(mid));+ return false;+ }+ };+ if (keys.length) await run(keys);+ };+ const entryOf = key => path.join(project, 'entries', `${key}.tsx`);++ await time('bundle', () =>+ batch(+ 'bundle',+ renderable().map(t => t.key),+ list =>+ vite.build({+ root: project,+ configFile: false,+ logLevel: 'silent',+ plugins: plugins(),+ resolve,+ define: {'process.env.NODE_ENV': '"production"'},+ build: {+ outDir: path.join(project, 'dist-client'),+ emptyOutDir: true,+ minify: false,+ reportCompressedSize: false,+ write: false,+ rollupOptions: {+ input: Object.fromEntries(list.map(k => [k, entryOf(k)])),+ preserveEntrySignatures: 'exports-only',+ external: ['react-dom/server'],+ },+ },+ }),+ ),+ );++ await time('render', async () => {+ const out = path.join(project, 'dist-ssr');+ const keys = renderable().map(t => t.key);+ await batch('render', keys, list =>+ vite.build({+ root: project,+ configFile: false,+ logLevel: 'silent',+ plugins: plugins(),+ resolve,+ ssr: {+ noExternal: true,+ resolve: {+ conditions: ['source', 'module', 'node', 'default'],+ externalConditions: ['source'],+ },+ },+ build: {+ ssr: true,+ outDir: out,+ emptyOutDir: false,+ minify: false,+ reportCompressedSize: false,+ rollupOptions: {+ input: Object.fromEntries(list.map(k => [k, entryOf(k)])),+ output: {format: 'esm', entryFileNames: '[name].mjs'},+ external: ['react', 'react-dom', 'react-dom/server', /^react\//],+ },+ },+ }),+ );+ for (const t of renderable()) {+ try {+ const m = await import(+ pathToFileURL(path.join(out, `${t.key}.mjs`)).href+ );+ const html = m.render();+ if (typeof html !== 'string')+ throw new Error('render returned no HTML');+ } catch (error) {+ fail(t.key, 'render', String(error.message ?? error).split('\n')[0]);+ }+ }+ });++ return {results: [...results.values()], timings};+}++/** The playground defaults a target's doc declares, or none. */+async function playgroundDefaults(packages, t) {+ const src = path.join(packages.get(t.pkg).dir, 'src');+ const rel = fs+ .readdirSync(src, {recursive: true})+ .map(String)+ .find(f => path.basename(f) === `${t.name}.doc.mjs`);+ if (!rel) return {};+ try {+ const m = await import(pathToFileURL(path.join(src, rel)).href);+ const doc =+ m.doc ??+ m.default ??+ Object.values(m).find(v => v && typeof v === 'object' && v.name);+ return JSON.parse(JSON.stringify(doc?.playground?.defaults ?? {}));+ } catch {+ return {};+ }+}++/** The module a copy's component is imported from. */+function entryFileOf(dir, name) {+ for (const f of ['index.ts', 'index.tsx', `${name}.tsx`, `${name}.ts`]) {+ const file = path.join(dir, f);+ if (fs.existsSync(file)) return file;+ }+ return null;+}diff --git a/packages/cli/test/swizzle-proof/samples.mjs b/packages/cli/test/swizzle-proof/samples.mjsnew file mode 100644index 0000000000..d77781bba7--- /dev/null+++ b/packages/cli/test/swizzle-proof/samples.mjs@@ -0,0 +1,537 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file samples.mjs+ * @input A copy's component, its module, and the package modules+ * @output One element per swizzle target whose playground defaults do not+ * render on their own+ * @position Read by the swizzle proof's entries; children and helpers come+ * from the copy's own module when it exports them+ */++const noop = () => {};+const ref = () => ({current: null});++function chartsSample(React, mod, Pkg, slot) {+ const h = React.createElement;+ const Chart = mod.Chart ?? Pkg.Chart;+ const bar = mod.bar ?? Pkg.bar;+ const data = [+ {month: 'Jan', revenue: 3},+ {month: 'Feb', revenue: 5},+ {month: 'Mar', revenue: 4},+ ];+ return h(Chart, {+ data,+ xKey: 'month',+ series: [bar('revenue', {label: 'Revenue'})],+ title: 'Revenue',+ ...slot,+ });+}++function labChart(React, mod, Pkg, props, child) {+ const h = React.createElement;+ const Chart = mod.Chart ?? Pkg.Chart;+ return h('div', {style: {width: 480, height: 320}}, h(Chart, props, child));+}++const monthly = {+ data: [+ {month: 'Jan', v: 1, upper: 30, lower: 10},+ {month: 'Feb', v: 3, upper: 40, lower: 20},+ {month: 'Mar', v: 2, upper: 50, lower: 30},+ ],+ xKey: 'month',+ yKeys: ['v', 'upper', 'lower'],+};+const xy = {+ data: [+ {x: 0, y: 1},+ {x: 1, y: 2},+ {x: 2, y: 3},+ ],+ xKey: 'x',+ yKeys: ['y'],+};+const ohlc = {+ data: [+ {day: '1', open: 1, close: 2, high: 3, low: 0.5},+ {day: '2', open: 2, close: 1.5, high: 2.5, low: 1},+ {day: '3', open: 1.5, close: 3, high: 3.5, low: 1.2},+ ],+ xKey: 'day',+ yKeys: ['high', 'low'],+};+const xyz = {+ data: [+ {x: 0, y: 1, z: 0},+ {x: 2, y: 2, z: 2},+ {x: 1, y: 3, z: 1},+ ],+ xKey: 'x',+ yKey: 'y',+ zKey: 'z',+};++function threeD(React, mod, Pkg, child) {+ const h = React.createElement;+ const ThreeDChart = mod.ThreeDChart ?? Pkg.ThreeDChart;+ return h(+ 'div',+ {style: {width: 600, height: 400}},+ h(ThreeDChart, xyz, child),+ );+}++function tour(React, Tour, TourStep) {+ const h = React.createElement;+ function Sample() {+ const a = React.useRef(null);+ const b = React.useRef(null);+ return h(+ React.Fragment,+ null,+ h('button', {type: 'button', ref: a}, 'Target A'),+ h('button', {type: 'button', ref: b}, 'Target B'),+ h(+ Tour,+ {isActive: true, onDismiss: noop},+ h(TourStep, {targetRef: a, heading: 'First'}, 'First body'),+ h(TourStep, {targetRef: b, heading: 'Second'}, 'Second body'),+ ),+ );+ }+ return h(Sample);+}++function navigation(React, Stack, Screen) {+ const h = React.createElement;+ return h(Stack, {+ label: 'Settings',+ root: h(+ Screen,+ {title: 'Settings'},+ h('button', {type: 'button'}, 'General'),+ ),+ path: [],+ onPathChange: noop,+ getKey: entry => entry,+ renderScreen: entry => h(Screen, {title: entry}, entry),+ });+}++export const samples = {+ core__AlertDialog: ({C, React}) =>+ React.createElement(C, {+ isOpen: true,+ onOpenChange: noop,+ title: 'Delete file?',+ description: 'This cannot be undone.',+ actionLabel: 'Delete',+ onAction: noop,+ }),+ core__CommandPalette: ({C, React}) => {+ const items = [+ {id: 'open', label: 'Open file'},+ {id: 'save', label: 'Save file'},+ ];+ return React.createElement(C, {+ isOpen: true,+ isInline: true,+ onOpenChange: noop,+ searchSource: {+ search: q =>+ items.filter(i => i.label.toLowerCase().includes(q.toLowerCase())),+ bootstrap: () => items,+ cancel: noop,+ },+ });+ },+ core__Heading: ({C, React}) =>+ React.createElement(C, {level: 2}, 'Section title'),+ core__Kbd: ({C, React}) => React.createElement(C, {keys: 'mod+k'}),+ core__SelectableCard: ({C, React}) =>+ React.createElement(C, {+ label: 'Standard shipping',+ isSelected: false,+ onChange: noop,+ }),+ core__Toast: ({C, React}) =>+ React.createElement(C, {body: 'Changes saved', onDismiss: noop}),+ core__Toolbar: ({C, React, Core}) =>+ React.createElement(C, {+ label: 'Table actions',+ size: 'sm',+ startContent: React.createElement(+ Core.TabList,+ {value: 'overview', onChange: noop},+ React.createElement(Core.Tab, {label: 'Overview', value: 'overview'}),+ React.createElement(Core.Tab, {label: 'Details', value: 'details'}),+ ),+ endContent: React.createElement(Core.Button, {label: 'Export'}),+ }),+ charts__Chart: ({React, mod, Pkg}) => chartsSample(React, mod, Pkg, {}),+ charts__ChartAxis: ({C, React, mod, Pkg}) =>+ chartsSample(React, mod, Pkg, {+ axes: React.createElement(+ React.Fragment,+ null,+ React.createElement(C, {position: 'bottom'}),+ React.createElement(C, {position: 'left'}),+ ),+ }),+ charts__ChartGrid: ({C, React, mod, Pkg}) =>+ chartsSample(React, mod, Pkg, {+ grid: React.createElement(C, {horizontal: true}),+ }),+ charts__ChartLegend: ({C, React, mod, Pkg}) =>+ chartsSample(React, mod, Pkg, {legend: React.createElement(C)}),+ charts__ChartTooltip: ({C, React, mod, Pkg}) =>+ chartsSample(React, mod, Pkg, {tooltip: React.createElement(C)}),+ lab__ChartArea: ({C, React, mod, Pkg}) =>+ labChart(+ React,+ mod,+ Pkg,+ monthly,+ React.createElement(C, {+ yUpper: 'upper',+ yLower: 'lower',+ color: '#0064E0',+ }),+ ),+ lab__ChartBar: ({C, React, mod, Pkg}) =>+ labChart(React, mod, Pkg, monthly, React.createElement(C, {dataKey: 'v'})),+ lab__ChartLine: ({C, React, mod, Pkg}) =>+ labChart(React, mod, Pkg, monthly, React.createElement(C, {dataKey: 'v'})),+ lab__ChartDot: ({C, React, mod, Pkg}) =>+ labChart(React, mod, Pkg, xy, React.createElement(C, {dataKey: 'y'})),+ lab__ChartDotGL: ({C, React, mod, Pkg}) =>+ labChart(+ React,+ mod,+ Pkg,+ xy,+ React.createElement(C, {dataKey: 'y', color: '#0064E0'}),+ ),+ lab__ChartDotGLInteractive: ({C, React, mod, Pkg}) =>+ labChart(+ React,+ mod,+ Pkg,+ xy,+ React.createElement(C, {dataKey: 'y', color: '#0064E0'}),+ ),+ lab__ChartCandlestick: ({C, React, mod, Pkg}) =>+ labChart(+ React,+ mod,+ Pkg,+ ohlc,+ React.createElement(C, {+ high: 'high',+ low: 'low',+ open: 'open',+ close: 'close',+ }),+ ),+ lab__ChartHeatmapGL: ({C, React, mod, Pkg}) =>+ labChart(+ React,+ mod,+ Pkg,+ {+ data: [+ {month: 'Jan', row: 'A', value: 1},+ {month: 'Jan', row: 'B', value: 2},+ {month: 'Feb', row: 'A', value: 3},+ {month: 'Feb', row: 'B', value: 4},+ ],+ xKey: 'month',+ yKeys: ['value'],+ },+ React.createElement(C, {+ xKey: 'month',+ yKey: 'row',+ valueKey: 'value',+ colorRange: ['#000000', '#ffffff'],+ }),+ ),+ lab__ChartStreamGL: ({C, React, mod, Pkg}) =>+ labChart(+ React,+ mod,+ Pkg,+ {data: [], xKey: 't', yKeys: ['v'], xDomain: [0, 10], yDomain: [0, 1]},+ React.createElement(C, {color: '#0064E0'}),+ ),+ lab__ChatReactionBar: ({C, React}) =>+ React.createElement(C, {+ reactions: [+ {emoji: '👍', count: 2, label: 'Thumbs up'},+ {emoji: '🎉', count: 1, isSelected: true, label: 'Party'},+ ],+ onReactionClick: noop,+ onAddReaction: noop,+ }),+ lab__Tour: ({C, React, mod, Pkg}) =>+ tour(React, C, mod.TourStep ?? Pkg.TourStep),+ lab__TourStep: ({C, React, mod, Pkg}) => tour(React, mod.Tour ?? Pkg.Tour, C),+ lab__CodeEditor: ({C, React}) =>+ React.createElement(C, {+ value: 'const answer = 42;',+ onChange: noop,+ language: 'typescript',+ label: 'Edit snippet',+ }),+ lab__CommentComposer: ({C, React}) =>+ React.createElement(C, {value: '', onChange: noop, onSubmit: noop}),+ lab__CommentPin: ({C, React}) =>+ React.createElement(C, {+ label: 'Open annotation from Ada',+ participants: [{id: 'ada', name: 'Ada Lovelace'}],+ onClick: noop,+ }),+ lab__CommentThread: ({C, React}) =>+ React.createElement(+ 'div',+ {style: {width: 320}},+ React.createElement(C, {+ comment: {+ id: 'margin',+ author: {id: 'maya', name: 'Maya Chen'},+ body: 'Should this say three days?',+ createdAt: '2026-09-30T19:00:00Z',+ },+ currentUser: {id: 'avery', name: 'Avery Kim'},+ onSubmit: noop,+ }),+ ),+ lab__DiffViewer: ({C, React, mod, Pkg}) => {+ const parse = mod.parseUnifiedDiff ?? Pkg.parseUnifiedDiff;+ const patch = [+ 'diff --git a/a.ts b/a.ts',+ '--- a/a.ts',+ '+++ b/a.ts',+ '@@ -1,2 +1,2 @@',+ ' const a = 1;',+ '-const b = 2;',+ '+const b = 3;',+ '',+ ].join('\n');+ return React.createElement(C, {file: parse(patch)[0]});+ },+ lab__ListInput: ({C, React, Core}) =>+ React.createElement(C, {+ label: 'Tags',+ value: [{id: '1', label: 'Alpha'}],+ onChange: noop,+ getItemKey: item => item.id,+ createItem: () => ({id: String(Date.now()), label: ''}),+ columns: [+ {+ key: 'label',+ header: 'Label',+ renderInput: ({item, label, isLabelHidden}) =>+ React.createElement(Core.TextInput, {+ label,+ isLabelHidden,+ value: item.label,+ onChange: noop,+ }),+ },+ ],+ }),+ lab__LogStream: ({C, React}) =>+ React.createElement(C, {+ entries: [+ {+ id: 'a',+ timestamp: '14:02:11.482',+ level: 'info',+ source: 'api-gateway',+ message: 'request accepted',+ },+ {+ id: 'b',+ timestamp: '14:02:12.001',+ level: 'warn',+ source: 'api-gateway',+ message: 'retrying upstream call',+ },+ ],+ }),+ lab__SankeyChart: ({C, React, mod, Pkg}) =>+ React.createElement(+ 'div',+ {style: {width: 480, height: 320}},+ React.createElement(+ C,+ {+ nodes: [+ {id: 'a', label: 'A', value: 10},+ {id: 'b', label: 'B', value: 10},+ {id: 'c', label: 'C', value: 10},+ ],+ links: [+ {source: 'a', target: 'b', value: 5},+ {source: 'b', target: 'c', value: 5},+ ],+ },+ React.createElement(mod.SankeyNode ?? Pkg.SankeyNode),+ ),+ ),+ lab__Schedule: ({C, React, mod, Pkg}) => {+ const view = (+ mod.createScheduleMonthlyView ?? Pkg.createScheduleMonthlyView+ )();+ return React.createElement(C, {+ view,+ events: [],+ date: Date.UTC(2026, 9, 30),+ focusDate: Date.UTC(2026, 9, 30),+ timezoneID: 'UTC',+ });+ },+ lab__ThreeDBar: ({C, React, mod, Pkg}) =>+ threeD(React, mod, Pkg, React.createElement(C, {color: '#00aa00'})),+ lab__ThreeDScatter: ({C, React, mod, Pkg}) =>+ threeD(React, mod, Pkg, React.createElement(C, {color: '#00aa00'})),+ lab__ThreeDScatterGL: ({C, React, mod, Pkg}) =>+ threeD(React, mod, Pkg, React.createElement(C, {color: '#00aa00'})),+ lab__ThreeDSurface: ({C, React, mod, Pkg}) =>+ threeD(React, mod, Pkg, React.createElement(C, {color: '#00aa00'})),+ lab__ThreeDChart: ({C, React, mod, Pkg}) =>+ React.createElement(+ 'div',+ {style: {width: 600, height: 400}},+ React.createElement(+ C,+ xyz,+ React.createElement(mod.ThreeDBar ?? Pkg.ThreeDBar, {color: '#00aa00'}),+ ),+ ),+ lab__TransferList: ({C, React}) =>+ React.createElement(C, {+ label: 'Columns',+ options: [+ {value: 'name', label: 'Name'},+ {value: 'status', label: 'Status'},+ {value: 'owner', label: 'Owner'},+ ],+ value: ['name'],+ onChange: noop,+ }),+ lab__NavigationStack: ({C, React, mod, Pkg}) =>+ navigation(React, C, mod.NavigationScreen ?? Pkg.NavigationScreen),+ lab__NavigationScreen: ({C, React, mod, Pkg}) =>+ navigation(React, mod.NavigationStack ?? Pkg.NavigationStack, C),+ lab__PageControl: ({C, React}) =>+ React.createElement(C, {+ totalPages: 3,+ page: 0,+ onChange: noop,+ label: 'Pages',+ }),+ lab__TabBarItem: ({C, React, mod, Pkg}) => {+ const TabBar = mod.TabBar ?? Pkg.TabBar;+ return React.createElement(+ TabBar,+ {value: 'home', onChange: noop, label: 'Sections'},+ React.createElement(C, {value: 'home', label: 'Home'}),+ React.createElement(C, {value: 'search', label: 'Search'}),+ );+ },+ core__ComplexSelector: ({C, React}) =>+ React.createElement(+ C,+ {label: 'Assignee', value: 'ada', onChange: noop, triggerLabel: 'Ada'},+ (value, onChange, close) =>+ React.createElement(+ 'button',+ {type: 'button', onClick: close},+ 'Pick ' + value,+ ),+ ),+ lab__SVGIcon: ({C, React, mod, Pkg}) =>+ React.createElement(C, {+ icon: mod.bellIcon ?? Pkg.bellIcon,+ 'aria-label': 'Notifications',+ }),+ richtext__RichTextEditorToolbar: ({C, React, mod, Pkg}) => {+ const Editor = mod.RichTextEditor ?? Pkg.RichTextEditor;+ return React.createElement(Editor, {+ label: 'Notes',+ toolbar: React.createElement(C),+ });+ },+ richtext__RichTextEditorAutoLinkPlugin: ({C, React, mod, Pkg}) => {+ const Editor = mod.RichTextEditor ?? Pkg.RichTextEditor;+ return React.createElement(Editor, {+ label: 'Notes',+ plugins: React.createElement(C),+ });+ },+ // Folders swizzle offers whose own name is not a component: each renders+ // a component the folder exports.+ core__Chat: ({React, mod}) =>+ React.createElement(+ mod.ChatMessage,+ {sender: 'user'},+ React.createElement(mod.ChatMessageBubble, null, 'Hello'),+ ),+ core__Indicator: ({React, mod}) =>+ React.createElement(mod.CheckboxIndicator, {isChecked: true}),+ core__Layer: ({React, mod, Core}) =>+ React.createElement(+ mod.LayerProvider,+ null,+ React.createElement(+ mod.Tooltip,+ {content: 'Hint'},+ React.createElement(Core.Button, {label: 'Hover'}),+ ),+ ),+ core__NavMenu: ({React, mod}) =>+ React.createElement(+ mod.NavHeadingMenu,+ {label: 'Products'},+ React.createElement(mod.NavHeadingMenuItem, {+ label: 'Overview',+ href: '#',+ }),+ ),+ core__Resizable: ({React, mod}) => {+ function Sample() {+ const resizable = mod.useResizable({defaultSize: mod.percent(50)});+ return React.createElement(mod.ResizeHandle, {+ resizable,+ label: 'Resize',+ });+ }+ return React.createElement(Sample);+ },+ core__SnapPaging: ({React, mod, Core}) => {+ function Sample() {+ const paging = mod.useSnapPaging();+ return React.createElement(+ Core.Carousel,+ {label: 'Photos', hasSnap: paging},+ React.createElement('div', null, 'One'),+ React.createElement('div', null, 'Two'),+ );+ }+ return React.createElement(Sample);+ },+};++/**+ * Folders swizzle offers that hold no component to render, with what they+ * hold. The proof still ejects and type-checks them.+ */+export const notRendered = {+ core__NavItem: 'a style module',+ core__InteractiveRoleContext: 'a context',+ core__SizeContext: 'a context',+};diff --git a/packages/cli/test/swizzle-proof/scope.test.mjs b/packages/cli/test/swizzle-proof/scope.test.mjsnew file mode 100644index 0000000000..53a83fa4ba--- /dev/null+++ b/packages/cli/test/swizzle-proof/scope.test.mjs@@ -0,0 +1,119 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file scope.test.mjs+ * @input A change as the proof reads it: the changed paths (or none when git+ * cannot read them), whether a toolchain path changed, the component+ * source that changed, and whether the checkout has a parent commit+ * @output Proves which targets the swizzle proof checks for each kind of run+ * (spec:AST-110 FR7)+ * @position Node test of proof.mjs's scope choice; reads no files+ */++import {describe, expect, it} from 'vitest';++import {proofScope} from './proof.mjs';++const component = ['packages/core/src/Button/Button.tsx'];++describe('which targets the swizzle proof checks', () => {+ it('checks nothing when no component source and no toolchain path changed', () => {+ expect(+ proofScope({+ changed: ['docs/README.md'],+ toolchain: undefined,+ relevant: [],+ hasParent: true,+ }).mode,+ ).toBe('none');+ });++ it('checks the affected targets of a pull request that changes component source', () => {+ expect(+ proofScope({+ changed: component,+ toolchain: undefined,+ relevant: component,+ hasParent: true,+ }).mode,+ ).toBe('affected');+ });++ it("checks the affected targets of main's run, diffed against its parent", () => {+ expect(+ proofScope({+ changed: component,+ toolchain: undefined,+ relevant: component,+ hasParent: true,+ }).mode,+ ).toBe('affected');+ });++ it('checks every target when a toolchain path changed', () => {+ const scope = proofScope({+ changed: ['packages/build/src/babel.js'],+ toolchain: 'packages/build/src/babel.js',+ relevant: [],+ hasParent: true,+ });+ expect(scope.mode).toBe('all');+ expect(scope.reason).toContain('packages/build/src/babel.js');+ });++ it('checks every target of a pull request whose change git cannot read', () => {+ const scope = proofScope({+ changed: null,+ toolchain: undefined,+ relevant: [],+ hasParent: true,+ });+ expect(scope.mode).toBe('all');+ expect(scope.reason).toMatch(/could not be read/);+ });++ it('checks every target of a local run whose change git cannot read', () => {+ expect(+ proofScope({+ changed: null,+ toolchain: undefined,+ relevant: [],+ hasParent: true,+ }).mode,+ ).toBe('all');+ });++ it('checks nothing in a checkout without a parent commit, and says why', () => {+ const scope = proofScope({+ changed: null,+ toolchain: undefined,+ relevant: [],+ hasParent: false,+ });+ expect(scope.mode).toBe('none');+ expect(scope.reason).toMatch(/no parent commit/);+ });++ it('checks every target when git fails in a checkout that has a parent, such as a merge-queue run', () => {+ expect(+ proofScope({+ changed: null,+ toolchain: undefined,+ relevant: [],+ hasParent: true,+ }).mode,+ ).toBe('all');+ });++ it('checks every target when asked for all of them', () => {+ expect(+ proofScope({+ changed: null,+ toolchain: undefined,+ relevant: [],+ hasParent: true,+ all: true,+ }).mode,+ ).toBe('all');+ });+});diff --git a/packages/cli/test/swizzle-proof/slice.mjs b/packages/cli/test/swizzle-proof/slice.mjsnew file mode 100644index 0000000000..f9e0910b19--- /dev/null+++ b/packages/cli/test/swizzle-proof/slice.mjs@@ -0,0 +1,64 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file slice.mjs+ * @input A slice index and the slice count+ * @output One Vitest case that runs that slice of the swizzle proof+ * (spec:AST-110 FR7). It prints each step's time, and fails with+ * each target's failure.+ * @position Shared by the swizzle-proof.<n>.test.mjs files, one per slice,+ * so the test-node shards split the proof between them+ */++import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import {describe, expect, it} from 'vitest';++import {runSlice} from './proof.mjs';+import {notRendered, samples} from './samples.mjs';++/** @param {number} index @param {number} count */+export function proveSlice(index, count) {+ describe(`swizzle proof, slice ${index + 1} of ${count}`, () => {+ it('ejects, type-checks, bundles and renders each affected target', async () => {+ const project = fs.mkdtempSync(+ path.join(os.tmpdir(), 'astryx-swizzle-proof-'),+ );+ try {+ const run = await runSlice({+ index,+ count,+ samples,+ notRendered,+ project,+ all: process.env.SWIZZLE_PROOF_ALL === '1',+ });+ const failures = run.results.filter(r => r.failure);+ console.log(+ `SWIZZLE_PROOF ${JSON.stringify({+ slice: `${index + 1}/${count}`,+ offered: run.offered,+ affected: run.affected,+ reason: run.reason,+ failed: failures.length,+ timings: run.timings,+ totalMs: run.totalMs,+ })}`,+ );+ for (const r of failures) {+ console.log(+ `SWIZZLE_PROOF_FAIL ${r.key} [${r.failure.step}] ${r.failure.error}`,+ );+ }+ expect(run.results.length).toBe(run.affected);+ expect(+ failures.map(r => `${r.key} [${r.failure.step}] ${r.failure.error}`),+ 'swizzle proof failures (spec:AST-110 FR7)',+ ).toEqual([]);+ } finally {+ fs.rmSync(project, {recursive: true, force: true});+ }+ }, 600_000);+ });+}diff --git a/packages/cli/test/swizzle-proof/swizzle-proof.1.test.mjs b/packages/cli/test/swizzle-proof/swizzle-proof.1.test.mjsnew file mode 100644index 0000000000..7b34046c99--- /dev/null+++ b/packages/cli/test/swizzle-proof/swizzle-proof.1.test.mjs@@ -0,0 +1,12 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file swizzle-proof.1.test.mjs+ * @input The change under test+ * @output Slice 1 of 8 of the swizzle proof (spec:AST-110 FR7)+ * @position One of eight files, so the test-node shards split the proof+ */++import {proveSlice} from './slice.mjs';++proveSlice(0, 8);diff --git a/packages/cli/test/swizzle-proof/swizzle-proof.2.test.mjs b/packages/cli/test/swizzle-proof/swizzle-proof.2.test.mjsnew file mode 100644index 0000000000..77a7184c73--- /dev/null+++ b/packages/cli/test/swizzle-proof/swizzle-proof.2.test.mjs@@ -0,0 +1,12 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file swizzle-proof.2.test.mjs+ * @input The change under test+ * @output Slice 2 of 8 of the swizzle proof (spec:AST-110 FR7)+ * @position One of eight files, so the test-node shards split the proof+ */++import {proveSlice} from './slice.mjs';++proveSlice(1, 8);diff --git a/packages/cli/test/swizzle-proof/swizzle-proof.3.test.mjs b/packages/cli/test/swizzle-proof/swizzle-proof.3.test.mjsnew file mode 100644index 0000000000..f91cbdcc12--- /dev/null+++ b/packages/cli/test/swizzle-proof/swizzle-proof.3.test.mjs@@ -0,0 +1,12 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file swizzle-proof.3.test.mjs+ * @input The change under test+ * @output Slice 3 of 8 of the swizzle proof (spec:AST-110 FR7)+ * @position One of eight files, so the test-node shards split the proof+ */++import {proveSlice} from './slice.mjs';++proveSlice(2, 8);diff --git a/packages/cli/test/swizzle-proof/swizzle-proof.4.test.mjs b/packages/cli/test/swizzle-proof/swizzle-proof.4.test.mjsnew file mode 100644index 0000000000..9f3febdd45--- /dev/null+++ b/packages/cli/test/swizzle-proof/swizzle-proof.4.test.mjs@@ -0,0 +1,12 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file swizzle-proof.4.test.mjs+ * @input The change under test+ * @output Slice 4 of 8 of the swizzle proof (spec:AST-110 FR7)+ * @position One of eight files, so the test-node shards split the proof+ */++import {proveSlice} from './slice.mjs';++proveSlice(3, 8);diff --git a/packages/cli/test/swizzle-proof/swizzle-proof.5.test.mjs b/packages/cli/test/swizzle-proof/swizzle-proof.5.test.mjsnew file mode 100644index 0000000000..ed68d296d8--- /dev/null+++ b/packages/cli/test/swizzle-proof/swizzle-proof.5.test.mjs@@ -0,0 +1,12 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file swizzle-proof.5.test.mjs+ * @input The change under test+ * @output Slice 5 of 8 of the swizzle proof (spec:AST-110 FR7)+ * @position One of eight files, so the test-node shards split the proof+ */++import {proveSlice} from './slice.mjs';++proveSlice(4, 8);diff --git a/packages/cli/test/swizzle-proof/swizzle-proof.6.test.mjs b/packages/cli/test/swizzle-proof/swizzle-proof.6.test.mjsnew file mode 100644index 0000000000..9433386724--- /dev/null+++ b/packages/cli/test/swizzle-proof/swizzle-proof.6.test.mjs@@ -0,0 +1,12 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file swizzle-proof.6.test.mjs+ * @input The change under test+ * @output Slice 6 of 8 of the swizzle proof (spec:AST-110 FR7)+ * @position One of eight files, so the test-node shards split the proof+ */++import {proveSlice} from './slice.mjs';++proveSlice(5, 8);diff --git a/packages/cli/test/swizzle-proof/swizzle-proof.7.test.mjs b/packages/cli/test/swizzle-proof/swizzle-proof.7.test.mjsnew file mode 100644index 0000000000..a0118c9b5d--- /dev/null+++ b/packages/cli/test/swizzle-proof/swizzle-proof.7.test.mjs@@ -0,0 +1,12 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file swizzle-proof.7.test.mjs+ * @input The change under test+ * @output Slice 7 of 8 of the swizzle proof (spec:AST-110 FR7)+ * @position One of eight files, so the test-node shards split the proof+ */++import {proveSlice} from './slice.mjs';++proveSlice(6, 8);diff --git a/packages/cli/test/swizzle-proof/swizzle-proof.8.test.mjs b/packages/cli/test/swizzle-proof/swizzle-proof.8.test.mjsnew file mode 100644index 0000000000..98c42335c8--- /dev/null+++ b/packages/cli/test/swizzle-proof/swizzle-proof.8.test.mjs@@ -0,0 +1,12 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file swizzle-proof.8.test.mjs+ * @input The change under test+ * @output Slice 8 of 8 of the swizzle proof (spec:AST-110 FR7)+ * @position One of eight files, so the test-node shards split the proof+ */++import {proveSlice} from './slice.mjs';++proveSlice(7, 8);