diff --git a/.github/workflows/bench.yaml b/.github/workflows/bench.yaml index d81e9a5ea..96a32325d 100644 --- a/.github/workflows/bench.yaml +++ b/.github/workflows/bench.yaml @@ -1,16 +1,5 @@ name: Bench -# Manual speed-gate runs that never publish: builds each listed commit's -# Linux x64 binary and dists in turn and runs that commit's verify:bench -# against the pinned reference release, all on one runner, so commits are -# compared on the same hardware; a commit older than verify:bench is measured -# with this workflow's harness. Each commit's receipt is uploaded under -# its position and ref, so a ref may repeat as a drift control. With -# `profile`, each commit's binary keeps its symbols and its large-closure -# load is also profiled, and those reports are uploaded beside its receipt. -# `cpu` and `attempts` start several runners and measure only on those with -# the named CPU, since ubuntu-latest does not choose the processor. - on: workflow_dispatch: inputs: @@ -104,18 +93,12 @@ jobs: n=$((n + 1)) echo "::group::$ref" git checkout --force --quiet "$ref" - # Each ref installs from its own lockfile into empty node_modules: - # bun keeps an earlier ref's packages as "no changes". The reference - # tarballs and cargo targets carry over. git clean -ffdxq -e .bench -e target if [ ! -f scripts/bench/run.ts ]; then - # Older than verify:bench: measured with this workflow's harness. git checkout "$GITHUB_SHA" -- scripts/bench scripts/consumers/measure.ts fi bun install ( - # A ref from before the v2 naming retired keeps its crate in - # crates/extract-v2. crate=packages/extract/crates/extractor [ -f "$crate/Cargo.toml" ] || crate=packages/extract/crates/extract-v2 cd "$crate" diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 39e3c8821..9454078fb 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -23,7 +23,6 @@ on: default: false jobs: - # ─── Fast lint (parallel with build-extract) ────────── lint: runs-on: ubuntu-latest steps: @@ -42,15 +41,6 @@ jobs: - name: Lint run: bunx vp run verify:lint - - name: NAPI loading contract check - run: | - if grep -rn "require('@animus-ui/extract')" packages/_integration/__tests__/; then - echo "ERROR: require('@animus-ui/extract') in _integration tests violates the NAPI loading contract." - echo "Use require('../../extract/extractor.js') instead. See packages/_integration/CLAUDE.md." - exit 1 - fi - - # ─── Rust unit tests (debug profile, no NAPI binary) ───── test-rust: runs-on: ubuntu-latest steps: @@ -73,7 +63,6 @@ jobs: - name: Rust unit tests run: bunx vp run verify:unit:rust - # ─── Strict Rust lint (parallel with test-rust) ──────────── clippy: runs-on: ubuntu-latest steps: @@ -98,7 +87,6 @@ jobs: - name: Clippy run: bunx vp run verify:clippy - # ─── Rust dependency hygiene (parallel with test-rust) ─── hygiene-rust: runs-on: ubuntu-latest steps: @@ -126,7 +114,6 @@ jobs: - name: Rust dependency hygiene run: bunx vp run verify:hygiene:rust - # ─── Rust NAPI build matrix (release profile, no tests) ── build-extract: strategy: fail-fast: false @@ -171,7 +158,6 @@ jobs: path: packages/extract/crates/extractor/*.node if-no-files-found: error - # ─── Full pipeline verification ───────────────────────── verify: needs: [build-extract, test-rust] runs-on: ubuntu-latest @@ -187,8 +173,6 @@ jobs: bun-version-file: .tool-versions - name: Download extractor linux binary - # @animus-ui/showcase#verify:build runs on the extractor — its binary is - # a hard precondition. uses: actions/download-artifact@v8 with: name: napi-extractor-x86_64-unknown-linux-gnu @@ -232,19 +216,6 @@ jobs: bunx vp run @animus-ui/showcase#verify:build bunx vp run @animus-ui/showcase#verify:assert - - name: Upload lane receipts - uses: actions/upload-artifact@v7 - with: - name: receipts-showcase - path: packages/showcase/.receipts/ - # .receipts is a dot-directory: upload-artifact excludes hidden - # files by default even when the path names the hidden dir (the - # v0.1.3 receipts outage; also the likely cause of the original - # empty verify-vite artifact). - include-hidden-files: true - if-no-files-found: error - - # ─── Next consumer lane (build + assert on every push) ── verify-next: needs: [build-extract] runs-on: ubuntu-latest @@ -276,19 +247,6 @@ jobs: bunx vp run @animus-ui/next-app#verify:assert bunx vp run @animus-ui/next-app#verify:prefixed - - name: Upload lane receipts - uses: actions/upload-artifact@v7 - with: - name: receipts-next - path: e2e/next-app/.receipts/ - # .receipts is a dot-directory: upload-artifact excludes hidden - # files by default even when the path names the hidden dir (the - # v0.1.3 receipts outage; also the likely cause of the original - # empty verify-vite artifact). - include-hidden-files: true - if-no-files-found: error - - # ─── Vite consumer lane (build + assert on every push) ── verify-vite: needs: [build-extract] runs-on: ubuntu-latest @@ -320,27 +278,8 @@ jobs: bunx vp run @animus-ui/vite-app#verify:assert bunx vp run @animus-ui/vite-app#verify:prefixed - - name: List lane receipts (diagnosing empty artifact) - # The receipt writes locally and next-app's analog uploads fine; - # this ls decides where the CI-side write goes missing. Flip the - # upload below to if-no-files-found: error once diagnosed. - run: ls -la e2e/vite-app/.receipts/ || echo "receipts dir absent" - - - name: Upload lane receipts - uses: actions/upload-artifact@v7 - with: - name: receipts-vite - path: e2e/vite-app/.receipts/ - # .receipts is a dot-directory: upload-artifact excludes hidden - # files by default even when the path names the hidden dir (the - # v0.1.3 receipts outage; also the likely cause of the original - # empty verify-vite artifact). - include-hidden-files: true - - # ─── Supported Worker consumer release gate ──────────── verify-workers: needs: [build-extract] - # Off by default to save CI minutes: runs only on an explicit dispatch with deploy_workers. if: github.event_name == 'workflow_dispatch' && inputs.deploy_workers == true runs-on: ubuntu-latest steps: @@ -365,13 +304,9 @@ jobs: - name: Build TS run: bunx vp run build:ts - - name: Verify Worker contracts - run: bunx vp run verify:workers:contracts - - name: Verify supported Workers run: bunx vp run --fail-if-no-match -F './e2e/*' -F '!@animus-ui/next-app' -F '!animus-packed-app' -F './packages/showcase' verify - # ─── Packed consumer lane (npm staging install on every push) ── verify-packed: needs: [build-extract] runs-on: ubuntu-latest @@ -400,23 +335,8 @@ jobs: - name: Packed consumer lane run: bunx vp run verify:packed - - name: Upload lane receipts - uses: actions/upload-artifact@v7 - with: - name: receipts-packed - path: e2e/packed-app/.staging/receipts/ - # .receipts is a dot-directory: upload-artifact excludes hidden - # files by default even when the path names the hidden dir (the - # v0.1.3 receipts outage; also the likely cause of the original - # empty verify-vite artifact). - include-hidden-files: true - if-no-files-found: error - - # ─── Speed gate (only where a release publishes) ──────── bench: needs: [build-extract] - # Paired timing against the pinned last-known-fast release: once per - # release, not on every push, to save CI minutes. if: >- (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')) || (github.event_name == 'workflow_dispatch' && inputs.publish_packages == true) @@ -448,9 +368,6 @@ jobs: - name: Fetch the pinned reference release run: bun scripts/bench/prepare.ts - # A row's ratio moves with the runner's CPU, so a row that fails or is - # unqualified here is measured again on a fresh runner (bench-confirm); - # an invalid row, or a run that does not finish, fails here. - name: Speed gate id: gate run: | @@ -467,9 +384,6 @@ jobs: include-hidden-files: true if-no-files-found: error - # The rows the speed gate did not pass, measured again on a fresh runner: - # the release proceeds only when each passes here. It runs wherever the - # gate does, and with nothing to confirm, no step runs. bench-confirm: needs: [build-extract, bench] runs-on: ubuntu-latest @@ -523,7 +437,6 @@ jobs: include-hidden-files: true if-no-files-found: error - # ─── Worker deployment (explicit dispatch only) ── deploy-workers: needs: [ @@ -574,7 +487,6 @@ jobs: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} run: bash scripts/deploy/workers.sh deploy - # ─── Release (tag push or manual dispatch only) ───────── release: needs: [ @@ -617,8 +529,6 @@ jobs: - run: bun install - name: Verify npm toolchain supports trusted publishing - # npm >= 11.5.1 is the OIDC floor; whoami is meaningless pre-publish - # under OIDC (credentials are minted at publish time). run: | node --version npm --version @@ -627,7 +537,6 @@ jobs: exit 1 fi - # ── Parse version from tag ── - name: Set version from tag id: version run: | @@ -645,17 +554,12 @@ jobs: echo "tag=$TAG" >> "$GITHUB_OUTPUT" echo "Publishing version: $VERSION (tag: $TAG)" - # ── Set version in all packages ── - name: Bump versions and resolve workspace deps run: bash scripts/set-release-version.sh "${{ steps.version.outputs.version }}" - # ── Build TS packages ── - name: Build run: bunx vp run build:ts - # ── Download all NAPI binaries ── - # A target missing its extractor binary fails the release job — - # never publish a partial matrix (engine-release-packaging). - name: Download darwin-arm64 extractor binary uses: actions/download-artifact@v8 with: @@ -674,7 +578,6 @@ jobs: name: napi-extractor-aarch64-unknown-linux-gnu path: packages/extract/crates/extractor/ - # ── Pack and verify one immutable release bundle ── - name: Pack immutable release bundle env: RELEASE_BUNDLE: ${{ runner.temp }}/animus-release-bundle @@ -686,12 +589,6 @@ jobs: exit 1 fi for pkg in properties core react effect-ui extract layergate vite-plugin next-plugin cli unplugin; do - # bun pm pack — the SAME packer verify:packed proves on every - # push (packer parity: npm pack shipped two release-only bugs in - # v0.1.2 because the lane packed differently). bun resolves a - # remaining workspace: specifier from the lockfile's version, not - # the release's, so set-release-version.sh above rewrites every - # block first (verify:packed packs this way on every push). (cd "packages/$pkg" && bun pm pack --destination "$RELEASE_BUNDLE") done for artifact in \ @@ -722,18 +619,12 @@ jobs: --expect-full-matrix bash scripts/verify/packed.sh --release-version "$VERSION" --tarballs-dir "$RELEASE_BUNDLE" - # ── Publish the verified bytes in dependency order ── - name: Publish immutable release bundle env: RELEASE_BUNDLE: ${{ runner.temp }}/animus-release-bundle run: | VERSION="${{ steps.version.outputs.version }}" NPM_TAG="${{ steps.version.outputs.tag }}" - # Re-runnable: a version npm already holds with these exact bytes is - # skipped, and a publish that errors after its upload landed counts - # once the registry shows the same bytes. Different bytes fail. - # Either way the release's dist-tag must name this version, or a newer - # one. Trusted publishing cannot move a tag, so a stale one fails. published_shasum() { npm view "@animus-ui/$1@${VERSION}" dist.shasum 2>/dev/null || true; } check_tag() { for attempt in 1 2 3 4 5 6 7 8 9 10; do diff --git a/.gitignore b/.gitignore index b3a0bc20c..57090e182 100644 --- a/.gitignore +++ b/.gitignore @@ -48,9 +48,6 @@ tsconfig.tsbuildinfo # NAPI build artifacts (binary only — index.js and index.d.ts are committed) *.node -# code-hygiene cascade postmortem audit (truncated per-run) -.hygiene/ - # Agents .claude # Shared Markdown tracker; this checkout keeps an ignored link. @@ -64,22 +61,13 @@ tsconfig.tsbuildinfo tmp -# Live oxlint test fixtures (scripts/hygiene/delete-unused.test.ts) are -# DELIBERATELY NOT ignored here. `vp lint --no-ignore` disables `.eslintignore` -# / `--ignore-path` / `--ignore-pattern` only — it does NOT disable .gitignore, -# so any fixture path listed here is skipped by the linter ("No files found to -# lint", number_of_files: 0) and the live-integration gate silently inspects -# nothing. The former `.live-test-fixtures-*` entry did exactly that. The tests -# create `livetestfixtures-*` at the repo root and remove them in a `finally`. - # packed consumer lane staging (verify:packed) e2e/packed-app/.staging/ -# per-lane verification receipts (verify:assert:* — increment 06) +# verify:browser-fixtures receipt .receipts/ -# internal notes stay ignored; the consumer contract page SHIPS -# (openspec: standalone-extraction-cli inc 07 — a bare `docs` dir pattern -# made the deliverable un-commitable; children-glob + negation instead) +# Local notes under docs/ stay ignored; the consumer contract page ships. +# A children glob, not a bare `docs` pattern, so the negation can apply. docs/* !docs/standalone-extraction.md # Personal agent configuration is linked from ~/.agents/projects/animus/. @@ -91,9 +79,8 @@ docs/* .collision-report.json .repowise/ -# OpenSpec planning lives in the shared store; only its pointer ships. -/openspec/* -!/openspec/config.yaml +# A failing parity run writes its report here +packages/_parity/last-failure.txt # local benchmark harness — generated fixture trees, oracles, and results # stay machine-local (narrow to packages/_bench/generated* if bench source diff --git a/.repowiseIgnore b/.repowiseIgnore index c2fd3a659..8facba094 100644 --- a/.repowiseIgnore +++ b/.repowiseIgnore @@ -1,6 +1,3 @@ -# Archived packages retained for reference only. -legacy/ - # NAPI-RS generated bindings. packages/extract/crates/extractor/index.d.ts diff --git a/AGENTS.md b/AGENTS.md index d96b900df..5ef80390b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,198 +4,166 @@ ## Workspace Topology -The repository has three top-level directories for code: +Code lives in two top-level directories: -- **`packages/`** — publishable libraries (`properties`, `core`, `react`, `effect-ui`, `extract`, `layergate`, `vite-plugin`, `next-plugin`, `cli`, `unplugin`; `layergate` is the framework-free vendor-stylesheet tool, with no Animus dependency, which the Vite plugin loads as an optional peer) and deep-internal private workspaces (`_assertions`, `_integration`, `_typescript-5.9`, `test-ds`, `showcase`, `oracle`). Everything here either ships to npm or is load-bearing for the build/verification pipeline. -- **`e2e/`** — consumer fixture applications whose test surface is "build the whole app, assert against output." Current members: `next-app` (Next.js), `next16-app`, `vite-app`, `vinext-app`, `react-router-app`, `packed-app`, and `rollup-app` (the standalone-CLI consumer lane). Future members may include `vite-app`, etc. Never published. -- **`legacy/`** — archived packages preserved for reference only. Do not install, build, or publish. See § Legacy Packages below for the full catalog. +- **`packages/`** — the published libraries `properties`, `core`, `react`, `effect-ui`, `extract`, `layergate`, `vite-plugin`, `next-plugin`, `cli` and `unplugin`, and the private workspaces `_assertions`, `_integration`, `_parity`, `_typescript-5.9`, `test-ds` and `showcase`. `layergate` has no Animus dependency; the Vite plugin loads it as an optional peer. +- **`e2e/`** — consumer applications that build against the packages and assert on the output: `effect-ui-app`, `next-app`, `next16-app`, `packed-app`, `react-router-app`, `rollup-app`, `svelte-app`, `vinext-app` and `vite-app`. None is published. `packed-app` is not a workspace: `vp run verify:packed` installs the packed tarballs into a copy of it. + +`scripts/` holds the verification, release and measurement scripts, and `tools/oxlint/anti-slop/` the repository's own lint rules. ### One-Way Dependency Rule -Dependencies flow top-down (consumer direction): - -- **`e2e/*` MAY import `packages/*`** — fixtures consume the libraries they verify. -- **`packages/*` MUST NOT import `e2e/*`** — libraries cannot depend on their downstream verifiers. -- **Neither `packages/*` nor `e2e/*` may import `legacy/*`** — the active graph must not depend on archived code. - -Assertion utilities that need to be importable by both `packages/*` post-build scripts and `e2e/*` fixtures live in `packages/_assertions/` (a `packages/`-resident private package), so imports always flow top-down without crossing the `packages/ ← e2e/` boundary. - -Enforced by `scripts/verify/topology.ts` (run in `vp run verify:lint`), which fails loud across all three vectors — source imports (relative paths and e2e workspace-name specifiers), tsconfig `paths` aliases, and `packages/* → e2e/*` `package.json` dependencies — listing every offending file. - -## Monorepo Build System - -### Package Build Order - -`extract` (Rust/NAPI) → `properties` → `system` → `layergate` → `vite-plugin`/`next-plugin` → `showcase`/`next-app`. TS packages use `tsdown && tsc -p tsconfig.build.json`; Rust uses `napi build --platform --release`. See per-package `AGENTS.md` for details. - -### TypeScript Implementations - -The package type-checks run on `bun check`, which reports the errors tsc does; declaration emit and the published-declaration checks run on stable TypeScript 7 (native compiler): - -| Workload | Implementation | Binary | Package | Pinned version | Install | -| ------------------------------------------------------------ | ----------------------------------- | ----------------------- | ------------ | ---------------- | ------------------------------------- | -| Type-check (`verify:compile`, `verify:types` source half) | `bun check` | `bun` | Bun | `.tool-versions` | (Bun itself) | -| Type-check (showcase, `verify:types` published half) | `tsc` (TypeScript 7 stable, native) | `node_modules/.bin/tsc` | `typescript` | `7.0.2` | `bun add -d --exact typescript@7.0.2` | -| Declaration emit (`build:ts` → `tsc -p tsconfig.build.json`) | `tsc` (TypeScript 7 stable, native) | `node_modules/.bin/tsc` | `typescript` | `7.0.2` | (same as above) | - -NOTE: `typescript@7` ships NO TS5 JS compiler API (`require('typescript')` is a version stub) — the hygiene cascade parses via the exact-pinned `oxc-parser` instead (`require_hygiene_parser` probes it). `scripts/verify/dts-parity.sh` is retained as re-runnable emit-parity scaffolding. - -### Verification Interface - -This `AGENTS.md` is the single authoritative contributor interface for verification. Per-package instructions link here and must not duplicate the workflow or diagnostic tables. The task graph lives in `vite.config.ts` under `run.tasks`; invoke migrated tasks with `vp run`, never `bun run `. `bun run` remains valid for unmigrated scripts such as `dev:showcase`, `test`, `lint`/`format`/`check`/`check:fix`, and `release`. - -#### Ordinary Workflows - -| Workflow | Command | Evidence | Explicit exclusions | -| ---------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Root fast | `vp run verify` | Lint/format, compile and type contracts, TS/Rust units, strict Clippy, the current-host NAPI canary, and global Worker contracts once | Does not materialize prerequisites or run parity, integration, Rust dependency hygiene, consumer production builds/assertions/dry-runs, packed proof, or CI's platform matrix | -| Root full | `vp run verify:full` | Materializes the extractor binary and TS dists; runs the root fast claim; runs every discovered consumer-owner claim; then parity, integration, Rust dependency hygiene, and packed proof | Complete only for the current host: it does not reproduce CI's multi-runner/cross-platform NAPI matrix, credentialed publication, or deployment | -| Package owner | `vp run @animus-ui/vite-app#verify` | The selected owner builds and asserts its production output; Worker owners also perform their credential-free upload dry-run | Does not materialize shared Rust/TS prerequisites or run root-global source checks and Worker contracts; substitute another supported owner package name as needed | -| Fail-closed dependents | `vp run --fail-if-no-match -F '...@animus-ui/vite-plugin' verify` | Complete owner claims for packages selected from current workspace dependency edges | Does not run unrelated owners or root-global diagnostics; `--fail-if-no-match` catches an empty selection, while the mandatory owner inventory catches a selected package that lacks `verify` | - -Every workspace-filtered command must include `--fail-if-no-match`. Do not combine `--filter`/`-F` with `--recursive`; Vite+ treats them as mutually exclusive. - -#### Atomic Diagnostics - -Atomic diagnostics are narrow, actionable leaves. They never materialize missing upstream artifacts. If one fails with `ERROR: X missing` or a `PREPARE:` line, run the exact remediation it prints, then rerun the diagnostic. Owner claims follow the same fail-loud rule and do not rebuild shared Rust or TS prerequisites. - -| Command | What it covers | Upstream requires | Fails loud when | Typical runtime | -| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------- | -| `vp run verify:lint` | `vp lint` + `vp fmt --check` (oxlint + oxfmt) + the workspace-topology boundary scan (`scripts/verify/topology.ts`) + the changelog entry check (`scripts/changelog/assemble.ts --check`) | `bun install` | lint or format violation, cross-boundary dependency, or a bad changelog entry | fast | -| `vp run verify:compile` | `bun check` across all packages (the showcase on `tsgo --noEmit`) | `bun install` | type error in any package `src/`, or in `extract/tests` or `vite-plugin/tests` | fast | -| `vp run verify:types` | type-contract tests via `tsconfig.test-d.json`, then consumer fixtures against the built `dist` declarations, with and without `exactOptionalPropertyTypes`, on TS 7.0.2 and 5.9.3, then the `animus types alias` packet contracts in `packages/cli/published` | `bun install`, `vp run build:ts` | an assertion fails, a published type widens or overflows, or `dist` is stale | medium | -| `vp run measure:type-budget` | a measurement, not a gate: instantiations, types and median check time of generated style-object fixtures and the open custom-property pin, against `scripts/type-budget/baseline.json` (`--write` re-records) | `bun install` | a fixture does not compile (never on a cost change) | slow | -| `vp run measure:consumers` | a measurement, not a gate: `-- --base --head --consumer ` runs each Vite app's build against both refs in a scratch copy and reports CSS and JS bytes, diagnostics by code and pruning | `bun install`, Rust, and installed consumer checkouts | an Animus ref does not build, or an app fails to bundle at both refs | slow | -| `vp run verify:bench` | the speed gate, outside every default tier: paired runs against the pinned last-known-fast release (`scripts/bench/releases.json`), each row gated on its own budget (native system load and native analysis: 5% or 50/20 ms; full `vite build` of `e2e/vite-app`: 10% or 100 ms) over one warm-up and nine scored pairs, extended once when inconclusive; rows: the generated issuer-shaped large-closure system, the showcase system and its captured analysis input, and the vite-app build; receipt in `.bench/receipts/`. `-- --candidate ` measures another built checkout; `-- --candidate-release ` a labelled diagnostic release | `bun scripts/bench/prepare.ts`, a fresh release-profile NAPI and `vp run build:ts` (in a `--candidate` checkout too), and no Rust build running | a row regresses past its budget, stays inconclusive (unqualified), or is invalid: a run fails, a side's receipt differs between runs, the candidate's output (digests, counts, diagnostics) differs from the reference's without an entry in `scripts/bench/accepted-differences.json`, or a fixture changes | medium | -| `bun scripts/bench/prepare.ts` | fetches the pinned reference and diagnostic releases into `.bench/releases/` and checks each tarball against its pinned sha512 | `npm` and the registry | a tarball cannot be fetched or does not match its pin | fast | -| `vp run verify:browser-fixtures` | custom-property semantics in headless Chromium through playwright-core: fixture pages' computed values against expectations, with a receipt in `.receipts/`; outside every default tier | the Chromium headless shell for playwright-core 1.63.0, `vp run build:ts`, and the built showcase (`vp run @animus-ui/showcase#verify:build`) | a probe's computed value differs, or the browser cannot launch | slow | -| `vp run verify:unit:rust` | `cargo test --lib` across the shared loader and extractor crates (debug profile) | Rust toolchain | Rust unit test fails | medium | -| `vp run verify:clippy` | `cargo clippy --workspace --all-targets --all-features -- -D warnings` across all active Rust crates | Rust toolchain with Clippy | any Rust or Clippy warning | medium | -| `vp run verify:unit:ts` | `bunx vp test run` (Vitest) on `core/__tests__`, `react/__tests__`, `effect-ui/__tests__`, `vite-plugin/tests`, `next-plugin/tests`, `properties/__tests__`, `layergate/__tests__`, `_assertions/__tests__`, `_parity/__tests__`, the engine-free `extract/tests` files, and the `scripts/verify` policy tests | `bun install` and a fresh extractor binary (`vp run build:extractor`) | TS unit test fails | fast | -| `vp run verify:coverage:ts` | aggregate per-file V8 coverage for the same TS targets as `verify:unit:ts`; emits text and lcov reports under `coverage/ts` (not per-test impact mapping) | `bun install` and a fresh extractor binary (`vp run build:extractor`) | TS unit test or coverage report generation fails | medium | -| `vp run verify:coverage:e2e` | V8 line coverage of `packages/*/src` code exercised by the next-app and vite-app production build+assert lanes; rebuilds TS dists with sourcemaps, emits `coverage/e2e/lcov.info`, then restores sourcemap-free dists | fresh extractor binary (fails loud with `PREPARE:`) | NAPI missing/stale, consumer build/assert fails, or report generation fails | slow | -| `vp run verify:workers:contracts` | structural, Worker behavior, and hydration contracts for all four Worker fixtures without production builds | `bun install` | root command/task contract or fixture test fails | fast | -| `vp run verify:hygiene:rust` | `cargo machete` dep-hygiene check across all active extraction Rust crates | `cargo-machete` binary on PATH | unused dep found (or machete missing) | fast | -| `vp run verify:canary` | extractor NAPI boundary snapshot tests + real-engine staticCss forced-emission evidence (`static-css-overrides.test.ts`) and property diagnostics (`property-diagnostics.test.ts`) | fresh extractor NAPI `.node` binary (mtime > Rust src) | NAPI binary missing or stale | medium | -| `vp run verify:parity` | extractor fresh-process/thread self-check, seam battery, and committed production/development oracle | fresh extractor NAPI `.node` + committed parity baselines | extractor input/baseline missing, stale, or divergent | medium | -| `vp run verify:integration` | full pipeline E2E in `packages/_integration/__tests__` | fresh NAPI + fresh `extract/dist/` + fresh `core/dist/` + fresh `react/dist/` | NAPI or any upstream dist missing/stale | medium | -| `vp run @animus-ui/next16-app#verify:build` | Next 16 consumer fixture build (Turbopack build mode) | fresh NAPI + fresh `extract/dist/` + fresh `core/dist/` + fresh `react/dist/` + fresh `next-plugin/dist/` | NAPI or any upstream dist missing/stale | slow | -| `vp run @animus-ui/next16-app#verify:assert` | positional assertions on Next 16 build output (TS, via `@animus-ui/assertions`) | `e2e/next16-app/.next/` + fresh `_assertions/dist/` | build output missing or assertions dist stale | fast | -| `vp run @animus-ui/next-app#verify:build` | Next consumer fixture build | fresh NAPI + fresh `extract/dist/` + fresh `core/dist/` + fresh `react/dist/` + fresh `next-plugin/dist/` | NAPI or any upstream dist missing/stale | slow | -| `vp run @animus-ui/showcase#verify:build` | showcase vite build | fresh NAPI + fresh `extract/dist/` + fresh `core/dist/` + fresh `react/dist/` + fresh `vite-plugin/dist/` + fresh `properties/dist/` | NAPI or any upstream dist missing/stale | slow | -| `vp run @animus-ui/vite-app#verify:build` | Vite consumer fixture build (`e2e/vite-app`) | fresh NAPI + fresh `extract/dist/` + fresh `core/dist/` + fresh `react/dist/` + fresh `vite-plugin/dist/` + fresh `properties/dist/` | NAPI or any upstream dist missing/stale | slow | -| `vp run @animus-ui/svelte-app#verify:build` | Svelte 5 client and SSR consumer fixture build (`e2e/svelte-app`) | fresh NAPI + fresh `extract/dist/` + fresh `core/dist/` + fresh `vite-plugin/dist/` + fresh `properties/dist/` | NAPI or any upstream dist missing/stale | medium | -| `vp run @animus-ui/vinext-app#verify:build` | Vinext App+Pages Worker production build | fresh extractor binary + fresh `extract/dist/`, `core/dist/`, `react/dist/`, `vite-plugin/dist/`, `properties/dist/`, and `test-ds/dist/` | NAPI or any upstream dist missing/stale | slow | -| `vp run @animus-ui/react-router-app#verify:build` | React Router v8 SSR Worker production build | fresh extractor binary + fresh `extract/dist/`, `core/dist/`, `react/dist/`, `vite-plugin/dist/`, `properties/dist/`, and `test-ds/dist/` | NAPI or any upstream dist missing/stale | slow | -| `vp run @animus-ui/next-app#verify:assert` | positional assertions on Next build output (TS, via `@animus-ui/assertions`) | `e2e/next-app/.next/` + fresh `_assertions/dist/` | build output missing or assertions dist stale | fast | -| `vp run @animus-ui/next-app#verify:prefixed` | builds `prefixed-variant/`, a nested Next project with `prefix` and `prefixContextualVars`, and asserts each contextual variable is emitted only under its prefixed name | fresh extractor binary + fresh `extract/dist/`, `core/dist/`, `react/dist/` and `next-plugin/dist/` | a declared name stays unprefixed, or no prefixed name is emitted | slow | -| `vp run @animus-ui/showcase#verify:assert` | positional assertions on showcase dist (TS, via `@animus-ui/assertions`) | `packages/showcase/dist/` + fresh `_assertions/dist/` | build output missing or assertions dist stale | fast | -| `vp run @animus-ui/vite-app#verify:assert` | positional assertions on Vite fixture dist (TS, via `@animus-ui/assertions`) | `e2e/vite-app/dist/` + fresh `_assertions/dist/` | build output missing or assertions dist stale | fast | -| `vp run @animus-ui/vite-app#verify:prefixed` | type-checks and builds `prefixed-variant/` with its own Vite config, `prefix` and `prefixContextualVars`, and asserts each contextual variable is emitted only under its prefixed name | fresh extractor binary + fresh `extract/dist/`, `core/dist/`, `react/dist/` and `vite-plugin/dist/` | a declared name stays unprefixed, or no prefixed name is emitted | slow | -| `vp run @animus-ui/svelte-app#verify:assert` | generated client CSS and production SSR attribute assertions for the Svelte fixture | `e2e/svelte-app/dist/` + fresh `_assertions/dist/` | build output missing, assertion dist stale, or CSS/runtime contract mismatch | fast | -| `vp run @animus-ui/vinext-app#verify:assert` | structural assertions on Vinext Worker output (TS, via `@animus-ui/assertions`) | `e2e/vinext-app/dist/` + fresh `_assertions/dist/` | build output missing or assertions dist stale | fast | -| `vp run @animus-ui/react-router-app#verify:assert` | structural assertions on React Router Worker output (TS, via `@animus-ui/assertions`) | `e2e/react-router-app/build/` + fresh `_assertions/dist/` | build output missing or assertions dist stale | fast | -| `vp run @animus-ui/showcase#verify:dry-run` | credential-free Wrangler validation for Worker `animus` | `packages/showcase/dist/` + matching app-owned Worker config | build output missing, Worker identity mismatch, or Wrangler rejects output | fast | -| `vp run @animus-ui/vite-app#verify:dry-run` | credential-free Wrangler validation for Worker `animus-vite-canary` | `e2e/vite-app/dist/` + matching app-owned Worker config | build output missing, Worker identity mismatch, or Wrangler rejects output | fast | -| `vp run @animus-ui/vinext-app#verify:dry-run` | credential-free Wrangler validation for Worker `animus-vinext-canary` | `e2e/vinext-app/dist/` + matching app-owned Worker config | build output missing, Worker identity mismatch, or Wrangler rejects output | fast | -| `vp run @animus-ui/react-router-app#verify:dry-run` | credential-free Wrangler validation for Worker `animus-react-router-canary` | `e2e/react-router-app/build/` + matching app-owned Worker config | build output missing, Worker identity mismatch, or Wrangler rejects output | fast | - -For domain-specific failure guidance, drill into `packages//AGENTS.md` after selecting a workflow or diagnostic here. +- `e2e/*` may import `packages/*`. +- `packages/*` must not import `e2e/*`. +- An `e2e/*` application must not import a sibling `e2e/*` application. -### Change-Type Map +Assertion helpers that both package scripts and e2e applications need live in `packages/_assertions`. -This map routes an edit to the smallest sufficient claim plus any source-owned diagnostics. Commands are written in execution order. - -Before pushing a change to `packages/extract/**` (the pipeline, the session, the engine or the system loader) or to a plugin (`packages/vite-plugin`, `packages/next-plugin`, `packages/unplugin`), also run `bun scripts/bench/prepare.ts && vp run verify:bench` and report its result. CI runs it once per release, where it gates publication. - -| You changed | Run | -| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `packages/core/src/**` | `vp run build:ts && vp run verify:compile && vp run verify:types && vp run verify:unit:ts` | -| `packages/react/src/**` | `vp run build:ts && vp run verify:compile && vp run verify:types && vp run verify:unit:ts` | -| `packages/effect-ui/src/**` | `vp run build:ts && vp run verify:compile && vp run verify:types && vp run verify:unit:ts && vp run @animus-ui/effect-ui-app#verify` | -| `packages/extract/crates/extractor/src/**` (incl. `css_keywords.json`, regenerated by `node packages/extract/scripts/css-keywords.ts --write`, and `property_table.json`, regenerated by `node packages/extract/scripts/property-table.ts --write`) | `vp run verify:clippy && vp run verify:hygiene:rust && vp run verify:unit:rust && vp run verify:canary && vp run verify:parity && vp run verify:integration` | -| `ANIMUS_LAYERS` in `pipeline/assemble-stylesheet.ts` (`node packages/extract/scripts/layer-order.ts --write` regenerates `layer_order.json`) | `vp run verify:clippy && vp run verify:hygiene:rust && vp run verify:unit:rust && vp run verify:canary && vp run verify:parity && vp run verify:integration` | -| `packages/extract/crates/system-loader/**` | `vp run verify:clippy && vp run verify:hygiene:rust && vp run verify:unit:rust && vp run verify:canary && vp run verify:parity && vp run verify:integration` | -| `packages/extract/crates/system-loader/src/extension_policy.json` (the one extension policy; TS reads it through `builtInExtensionPolicy()`, and `extract/tests/extension-policy.test.ts` pins it) | `vp run verify:unit:ts`, then the `system-loader/**` row | -| `packages/extract/scripts/node-builtins.ts` (`--write`, under Node 24, regenerates `crates/extractor/src/node_builtins.json` from `module.builtinModules`: rerun it when the pinned Node major changes; `--check` reports a stale one) | `node packages/extract/scripts/node-builtins.ts --check`, then the `extractor/src/**` row | -| `packages/extract/pipeline/**` (extractor TS binding / pipeline) | `vp run verify:compile && vp run verify:canary && vp run verify:integration` | -| `packages/extract/crates/extractor/Cargo.toml` | `vp run verify:clippy && vp run verify:hygiene:rust && vp run verify:unit:rust` | -| `packages/_parity/**` (parity harness + corpus) | `vp run verify:unit:ts && vp run verify:parity` | -| `knip.config.ts` | `vp run hygiene` | -| `scripts/hygiene/**` | `bunx vp test run scripts/hygiene/ && vp run hygiene` | -| `scripts/changelog/**` or `changes/unreleased/**` | `vp run verify:lint` | -| `packages/vite-plugin/src/**` | `vp run verify:compile && vp run verify:integration && vp run --fail-if-no-match -F '...@animus-ui/vite-plugin' verify` | -| `packages/next-plugin/src/**` | `vp run verify:compile && vp run verify:unit:ts && vp run @animus-ui/next-app#verify` | -| `packages/_assertions/src/**` | `vp run verify:unit:ts && vp run --fail-if-no-match -F './e2e/*' -F '!animus-packed-app' -F './packages/showcase' verify` | -| `e2e/next-app/src/**` | `vp run @animus-ui/next-app#verify` | -| `e2e/next16-app/**` | `vp run @animus-ui/next16-app#verify` | -| `e2e/rollup-app/**` | `vp run @animus-ui/rollup-app#verify` | -| `packages/extract/session/**` (driver-shared session engine) | `vp run verify:compile && vp run verify:unit:ts && vp run verify:integration && vp run @animus-ui/rollup-app#verify` | -| `packages/unplugin/src/**` | `vp run verify:compile && vp run verify:unit:ts && vp run @animus-ui/rollup-app#verify` | -| `packages/cli/**` | `vp run verify:compile && vp run verify:unit:ts && vp run build:ts && vp run verify:types && vp run @animus-ui/rollup-app#verify && vp run verify:packed` | -| `packages/oracle/**` | `vp run verify:compile && vp run verify:unit:ts` | -| `e2e/vite-app/**` | `vp run verify:workers:contracts && vp run @animus-ui/vite-app#verify` | -| `e2e/svelte-app/**` | `vp run @animus-ui/svelte-app#verify` | -| `e2e/effect-ui-app/**` | `vp run @animus-ui/effect-ui-app#verify` | -| `e2e/vinext-app/**` | `vp run verify:workers:contracts && vp run @animus-ui/vinext-app#verify` | -| `e2e/react-router-app/**` | `vp run verify:workers:contracts && vp run @animus-ui/react-router-app#verify` | -| `packages/showcase/src/**` (code; MDX content excluded — see sidebar) | `vp run @animus-ui/showcase#verify` | -| `packages/showcase/wrangler.jsonc` | `vp run verify:workers:contracts && vp run @animus-ui/showcase#verify` | -| `packages/properties/src/**` | `vp run verify:compile && vp run verify:unit:ts` | -| `packages/layergate/src/**` (the core and its Vite and webpack adapters) | `vp run verify:compile && vp run verify:unit:ts` | -| `packages/properties/src/unitless.ts` (the unitless and vendor-prefix table the extractor includes) | `node packages/extract/scripts/property-table.ts --write && vp run verify:compile && vp run verify:unit:ts`, then the `extractor/src/**` row | -| `packages/_integration/__tests__/**` | `vp run verify:integration` | -| `packages/test-ds/src/**` | `vp run verify:unit:ts && vp run --fail-if-no-match -F '...@animus-ui/test-ds' verify` | -| `e2e/packed-app/**` or `scripts/verify/packed.sh` | `vp run verify:packed` | -| `scripts/verify/topology.*` | `vp run verify:lint` | -| `tools/oxlint/anti-slop/**` | `vp run verify:lint && vp run verify:compile` | -| `packages/{properties,core,react,effect-ui,extract,layergate,vite-plugin,next-plugin,cli,unplugin}/package.json` (deps, peers, exports, files) | `vp run verify:packed` | -| `.github/workflows/ci.yaml`, `scripts/**`, `.tool-versions` | `vp run verify:full` | -| Worker orchestration (`vite.config.ts`, `scripts/verify/**`, root deploy scripts, Worker ignores) | `vp run verify:full` | -| Broad refactor across multiple surfaces | `vp run verify:full` | - -**No verify tier required** for: - -- `openspec/**` — use `openspec validate ` instead -- MDX content under `packages/showcase/src/content/**` -- Root markdown (`AGENTS.md`, `README.md`, `docs/**`) - -**Ownership rule**: any change introducing a new top-level edit surface (e.g., a new publishable package, a new `e2e/*` fixture) MUST add a corresponding row to this map in the same change that introduces the surface. +`scripts/verify/topology.ts`, part of `vp run verify:lint`, enforces the rule over source imports, tsconfig `paths` aliases and `package.json` dependencies, and lists every offending file. -### Cache Tiers +## Build + +`vp run build:all` builds the extractor binary (`build:extractor`), then every package's `build:ts`. `vp run build:extract` builds the binary and the `extract` package only. + +- The binary: `scripts/cloudflare/build-extractor.sh` checks that `rustc` matches the channel in `packages/extract/crates/extractor/rust-toolchain.toml`, then runs `napi build --platform --no-js --release`. +- TypeScript packages: `tsdown`; packages whose `build:ts` also runs `tsc -p tsconfig.build.json` emit their declarations with it. + +### TypeScript + +| Workload | Compiler | +| ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | +| Package type-check (`compile` script, run by `verify:compile`) | `bun check`; the showcase uses `tsc --noEmit` | +| Type tests against source (`verify:types`) | `bun check -p packages//types/source/tsconfig.test-d.json` | +| Type tests against built declarations (`verify:types`), e2e `verify:tsc` | `node_modules/.bin/tsc`, `typescript` 7.0.2; `verify:types` repeats the published checks on TypeScript 5.9.3 from `packages/_typescript-5.9` | +| Declaration emit (`build:ts`) | `tsdown`, or `tsc -p tsconfig.build.json` where `build:ts` names it | + +`typescript` 7 has no JavaScript compiler API: `require('typescript')` exports only `version` and `versionMajorMinor`. Scripts that parse TypeScript use the exact-pinned `oxc-parser`. + +## Verification + +This file is the one place that lists verification commands; per-package `CLAUDE.md` files point here. The root tasks are defined in `run.tasks` in `vite.config.ts`, and each owner package defines its own `verify` script. Run them with `vp run`. -`clean:light` — `.vite` + `dist/` (<1s); use when transforms seem stale. `clean:full` — adds Rust `target/` + `.node` binary (30-60s rebuild); use for NAPI errors or "nothing works." `clean` — legacy alias for `dist/` + `target/`. +### Ordinary Workflows -Every `verify:build` and `verify:prefixed` builds through `scripts/verify/build-consumer.sh [script] [build root]`, which first removes exactly `.animus`, `.next`, `build`, `dist` and `tsconfig.tsbuildinfo` directly under the root it builds. Other ignored state, such as `.svelte-kit`, `.react-router`, `.wrangler` and `out`, stays; clear it by hand when it matters. It removes nothing, and fails, unless git ignores every file in that output. +| Workflow | Command | What it runs | +| ---------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Root fast | `vp run verify` | `verify:lint`, `verify:compile`, `verify:types`, `verify:unit:ts`, `verify:unit:rust`, `verify:clippy` and `verify:canary`. It builds nothing, so the extractor binary and the package dists must already be fresh. | +| Root full | `vp run verify:full` | `build:extractor`, `build:ts`, `verify`, the `verify` of every e2e application except `packed-app` and of the showcase, then `verify:parity`, `verify:integration`, `verify:hygiene:rust` and `verify:packed`. Complete for the current host only: CI's cross-platform binary matrix, publication and deployment are not reproduced. | +| One owner | `vp run @animus-ui/vite-app#verify` | That package's build and assertions (see Owner Claims). Substitute any owner package name. | +| Dependents | `vp run --fail-if-no-match -F '...@animus-ui/vite-plugin' verify` | The `verify` of every package that depends on the named one. | -### Debugging Quick-Ref +Give every filtered command `--fail-if-no-match`: without it, a filter that matches nothing exits 0. `vp run` rejects `--filter`/`-F` combined with `--recursive`. -Symptom-to-fix table for extraction-pipeline failures: see [`packages/extract/AGENTS.md`](packages/extract/AGENTS.md) § Debugging Quick-Ref. +### Atomic Diagnostics -### Key Rules +Each diagnostic checks its preconditions and never builds them. When one fails with `ERROR: … Run: ` or `PREPARE: `, run that command, then rerun the diagnostic. -- **bun for package-management; vp for task orchestration; Node 24.22 LTS for repository and Workers builds.** `bun install`, `bun.lock`, `bun run --filter` per-package dispatch all stay bun-side. Migrated tiers (verify:_, build:_, hygiene) dispatch via `vp run X`. Bun version is pinned in `.tool-versions` (consumed by CI via `bun-version-file`); Node is pinned to 24.22.1 in `.tool-versions` (consumed by CI via `node-version-file`) and mirrored in `.node-version` for Cloudflare Workers Builds. Node 24.22.1 satisfies the React Router v8 canary and vp's native TypeScript-strip requirement. `vp run` works on Node 20 (it uses the Vite-bundled loader) but the rest of the vp surface requires Node 22+. Never npm/npx. -- **vp env stays disabled.** `vp env use` SHALL NOT be invoked locally or in CI for this repo. `.tool-versions` is the sole bun-version source of truth (vp env injection broke tsdown's `unrun` resolver in PoC session 92). Note: `vp run` puts the bun named by `package.json` `packageManager` first on PATH, so keep `packageManager: bun@1.4.3` equal to `.tool-versions: bun 1.4.3`; `.tool-versions` remains authoritative for asdf/mise/CI. -- **Bun 1.3.12–1.3.14 `createRequire` bug, fixed in the pinned 1.4.3** — `createRequire(import.meta.url)` matched the `"types"` export condition as runtime and loaded `.d.ts` files as JS. On 1.4.3 it selects `require`/`default` as Node does, so `require('@scope/pkg')` is safe again; direct relative paths written as the old workaround still work. -- **No React resolve aliases** — they break the extraction transform pipeline. Aliasing `react`/`react-dom` forces React to an absolute path outside the package, which disrupts vite's module graph ordering: the transform hook fires and returns correct code, but vite's bundler uses the original untransformed source. Silent failure (zero errors, zero warnings). For React deduplication, use bun workspace hoisting, `package.json` `overrides`, or vite `dedupe` (separate from `resolve.alias`). -- **Extraction runs in production AND dev.** Restart the dev server to pick up system changes (buildStart results held in memory). -- **Atomic tiers fail loud, never silently rebuild.** On `ERROR: X missing. Run: vp run build:extract` (or similar), run that command and retry. Tiers never invoke upstream builds themselves. +| Command | What it checks | Needs | +| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | +| `vp run verify:lint` | `vp lint` (oxlint), `vp fmt --check` (oxfmt, Markdown included), the topology scan (`scripts/verify/topology.ts`) and `scripts/changelog/assemble.ts --check` | `bun install` | +| `vp run verify:compile` | every package's `compile` script (`scripts/verify/compile.sh`) | `bun install`; `react` and `effect-ui` read `core`'s built declarations | +| `vp run verify:types` | `scripts/verify/types.sh`: each package's `types/source` tests; the consumer fixtures in `packages/{core,react,effect-ui,test-ds}/types/published` against the built declarations, with and without `exactOptionalPropertyTypes`, on TypeScript 7 and 5.9; then the `animus types alias` packet contracts in `packages/cli/published` | fresh dists of `core`, `react`, `effect-ui`, `test-ds` and `extract` (`vp run build:ts`) | +| `vp run verify:unit:ts` | Vitest over `typescriptTestTargets` in `vite.config.ts`: `packages/core`, `packages/react`, `packages/vite-plugin/tests`, `packages/next-plugin/tests`, `packages/cli/tests`, `packages/unplugin/tests`, `packages/layergate/__tests__`, `packages/extract/tests/session`, and `bundle-removal`, `css-keywords` and `property-table` in `packages/extract/tests` | a fresh extractor binary (`vp run build:extractor`); `react`'s tests read `core`'s dist | +| `vp run verify:coverage:ts` | the same targets under V8 coverage; text and lcov reports in `coverage/ts` | as `verify:unit:ts` | +| `vp run verify:unit:rust` | `cargo test --lib` in both crates under `packages/extract/crates` | the Rust toolchain | +| `vp run verify:clippy` | `scripts/verify/rust-policy.ts` (no blanket `allow`/`expect` of warnings; equal `[lints]` tables in both crates), then `cargo clippy --workspace --all-targets --all-features -- -D warnings` in both crates | the Rust toolchain with Clippy | +| `vp run verify:hygiene:rust` | an empty `cargo-machete` ignore list in both crates, then `cargo machete` | `cargo-machete` on `PATH` | +| `vp run verify:canary` | the extractor tests that drive the real binary, listed in `scripts/verify/canary.sh`, under `bun test` | a fresh extractor binary | +| `vp run verify:parity` | `packages/_parity`: the fresh-process and threaded self-checks, the seam battery against `tools/seam-baseline.json`, and both modes against the committed baselines in `baselines/extractor` | a fresh extractor binary | +| `vp run verify:integration` | the pipeline tests in `packages/_integration/__tests__` | a fresh extractor binary; fresh dists of `extract`, `core` and `react` | +| `vp run verify:packed` | `scripts/verify/packed.sh`: packs the ten published packages as a release does, checks their internal versions, `publint` and `attw`, installs them with npm into a copy of `e2e/packed-app`, loads every entry, type-checks and builds it with Vite and Next, and repeats the install outside the repository for the Svelte path | a fresh `_assertions` dist; for local tarballs, a fresh binary and all ten dists; `npm` | +| `vp run verify:coverage:e2e` | V8 line coverage of `packages/*/src` through the builds and assertions of `next-app`, `vite-app`, the showcase, `vinext-app` and `react-router-app`; rebuilds the dists with source maps, writes `coverage/e2e/lcov.info`, then rebuilds them without | a fresh extractor binary | +| `vp run verify:browser-fixtures` | the custom-property fixtures in headless Chromium through `playwright-core`; writes `.receipts/browser-fixtures.json`; outside every tier | the Chromium headless shell for `playwright-core` 1.64.0, a fresh binary, `vp run build:ts`, and the built showcase | +| `vp run verify:bench` | the speed gate, outside every tier: paired runs against the pinned release in `scripts/bench/releases.json`, each row against its budget in `scripts/bench/protocol.ts`; a candidate whose output differs from the reference's fails unless `scripts/bench/accepted-differences.json` explains it; receipt in `.bench/receipts/`. `-- --candidate ` measures another built checkout | `bun scripts/bench/prepare.ts` (fetches and checks the pinned releases into `.bench/releases/`); a release-profile binary and fresh dists | +| `vp run measure:type-budget` | a measurement: instantiations, types and check time of generated style-object fixtures against `scripts/type-budget/baseline.json` (`-- --write` re-records it); fails only when a fixture does not compile | `bun install` | +| `vp run measure:consumers` | a measurement: `-- --base --head --consumer ` builds each consumer against both refs in a scratch copy and reports CSS and JS bytes, diagnostics and pruning | Rust, and the consumer checkouts (or `scripts/consumers/consumers.local.json`) | + +### Owner Claims + +Each owner's `verify` script runs these steps in order. Run a step alone as `vp run #`. + +| Owner | `verify` steps | +| ----------------------------- | ---------------------------------------------------------------------------------------------------------------- | +| `@animus-ui/showcase` | `verify:build`, `verify:assert`, `verify:dry-run` (Worker `animus`) | +| `@animus-ui/vite-app` | `verify:build`, `verify:tsc`, `verify:assert`, `verify:dry-run` (Worker `animus-vite-canary`), `verify:prefixed` | +| `@animus-ui/next-app` | `verify:build`, `verify:tsc`, `verify:assert`, `verify:prefixed` | +| `@animus-ui/next16-app` | `verify:build`, `verify:assert` | +| `@animus-ui/vinext-app` | `verify:build`, `verify:assert`, `verify:dry-run` (Worker `animus-vinext-canary`) | +| `@animus-ui/react-router-app` | `verify:build`, `verify:assert`, `verify:dry-run` (Worker `animus-react-router-canary`) | +| `@animus-ui/svelte-app` | `verify:build`, `verify:tsc`, `verify:assert` | +| `@animus-ui/effect-ui-app` | `verify:build`, `verify:tsc`, `verify:assert` | +| `@animus-ui/rollup-app` | `verify:build` (the `animus` CLI, then Rollup), `verify:assert` | + +- `verify:build` runs `scripts/verify/build-consumer.sh`: it removes `.animus`, `.next`, `build`, `dist` and `tsconfig.tsbuildinfo` directly under the build root, and refuses when git does not ignore everything in them. Other ignored state, such as `.svelte-kit`, `.react-router`, `.wrangler` and `out`, stays. It then requires a fresh extractor binary and fresh dists of every workspace package the owner depends on, and prints `PREPARE:` with the build commands when one is missing. +- `verify:tsc` runs `tsc --noEmit` on the application's own tsconfig. +- `verify:assert` requires the build output and a fresh `_assertions` dist, then runs the application's assertion script (`rollup-app` runs its `scripts/assert-*.mjs` directly). +- `verify:dry-run` checks the Worker name in `wrangler.jsonc`, then runs `wrangler deploy --dry-run` without credentials. +- `verify:prefixed` builds the `prefixed-variant/` project with `prefix` and `prefixContextualVars` and asserts every contextual variable is emitted only under its prefixed name. + +### Change-Type Map + +The commands to run for each edit surface, in order. Package-level guidance is in the `CLAUDE.md` beside the code. + +Before pushing a change to `packages/extract/**` or to a plugin (`packages/vite-plugin`, `packages/next-plugin`, `packages/unplugin`), also run `bun scripts/bench/prepare.ts && vp run verify:bench` and report its result. + +| You changed | Run | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `packages/core/src/**` | `vp run build:ts && vp run verify:compile && vp run verify:types && vp run verify:unit:ts` | +| `packages/react/src/**` | `vp run build:ts && vp run verify:compile && vp run verify:types && vp run verify:unit:ts` | +| `packages/effect-ui/src/**` | `vp run build:ts && vp run verify:compile && vp run verify:types && vp run @animus-ui/effect-ui-app#verify` | +| `packages//types/**` (type tests) | `vp run build:ts && vp run verify:types` | +| `packages/properties/src/**` | `vp run verify:compile && vp run build:ts && vp run verify:unit:ts` | +| `packages/properties/src/unitless.ts` (the table the extractor includes) | `node packages/extract/scripts/property-table.ts --write && vp run verify:compile && vp run verify:unit:ts`, then the `extractor/src/**` row | +| `packages/extract/crates/extractor/src/**`, including `css_keywords.json` (`node packages/extract/scripts/css-keywords.ts --write`) and `property_table.json` (`node packages/extract/scripts/property-table.ts --write`) | `vp run verify:clippy && vp run verify:hygiene:rust && vp run verify:unit:rust && vp run build:extract && vp run verify:canary && vp run verify:parity && vp run verify:integration` | +| `ANIMUS_LAYERS` in `packages/extract/pipeline/assemble-stylesheet.ts` (`node packages/extract/scripts/layer-order.ts --write` regenerates `layer_order.json`) | the `extractor/src/**` row | +| `packages/extract/scripts/node-builtins.ts` (`--write`, under Node 24, regenerates `node_builtins.json`; rerun it when the pinned Node major changes) | `node packages/extract/scripts/node-builtins.ts --check`, then the `extractor/src/**` row | +| `packages/extract/crates/system-loader/**` | the `extractor/src/**` row | +| `packages/extract/crates/extractor/Cargo.toml` | `vp run verify:clippy && vp run verify:hygiene:rust && vp run verify:unit:rust` | +| `packages/extract/pipeline/**` | `vp run verify:compile && vp run verify:unit:ts && vp run verify:canary && vp run build:ts && vp run verify:integration` | +| `packages/extract/session/**` | `vp run verify:compile && vp run verify:unit:ts && vp run build:ts && vp run verify:integration && vp run @animus-ui/rollup-app#verify` | +| `packages/_parity/**` | `vp run verify:compile && vp run verify:parity` | +| `packages/_integration/**` | `vp run verify:integration` | +| `packages/vite-plugin/src/**` | `vp run verify:compile && vp run verify:unit:ts && vp run build:ts && vp run verify:integration && vp run --fail-if-no-match -F '...@animus-ui/vite-plugin' verify` | +| `packages/next-plugin/src/**` | `vp run verify:compile && vp run verify:unit:ts && vp run build:ts && vp run @animus-ui/next-app#verify && vp run @animus-ui/next16-app#verify` | +| `packages/unplugin/src/**` | `vp run verify:compile && vp run verify:unit:ts && vp run build:ts && vp run @animus-ui/rollup-app#verify` | +| `packages/cli/**` | `vp run verify:compile && vp run verify:unit:ts && vp run build:ts && vp run verify:types && vp run @animus-ui/rollup-app#verify && vp run verify:packed` | +| `packages/layergate/src/**` | `vp run verify:compile && vp run verify:unit:ts` | +| `packages/_assertions/src/**` | `vp run build:ts && vp run --fail-if-no-match -F './e2e/*' -F '!animus-packed-app' -F './packages/showcase' verify` | +| `packages/test-ds/src/**` | `vp run build:ts && vp run verify:types && vp run --fail-if-no-match -F '...@animus-ui/test-ds' verify` | +| `packages/showcase/**` | `vp run @animus-ui/showcase#verify` | +| `e2e//**` (except `packed-app`) | `vp run @animus-ui/#verify` | +| `e2e/packed-app/**`, `scripts/verify/packed.sh`, or a published package's `package.json` (dependencies, peers, exports, files) | `vp run verify:packed` | +| `scripts/verify/topology.ts`, `scripts/changelog/**`, any Markdown file | `vp run verify:lint` | +| `tools/oxlint/anti-slop/**` | `vp run verify:lint && vp run verify:compile` | +| `knip.config.ts` | `bunx knip` | +| `vite.config.ts`, `.github/workflows/**`, other `scripts/**`, `.tool-versions`, or a change across several surfaces | `vp run verify:full` | + +A change that adds an edit surface, such as a published package or an e2e application, adds its row here in the same change. + +### Cache Tiers -### Changelog Entries +- `vp run clean:light` removes `node_modules/.vite` and `packages/*/dist`; use it when transforms look stale. +- `vp run clean:full` also removes both crates' `target/` directories and the extractor `.node` binary; the Rust rebuild takes 30–60 s. +- `vp run clean` removes `packages/*/dist` and both crates' `target/` directories. +- `bun run rebuild` runs `clean:full`, then `build:all`. -Changelog entries are paused until 1.0.0. A change adds no file under `changes/unreleased/` and does not edit `CHANGELOG.md`. A user-visible or breaking change states its release note in the PR body instead, and the release notes are written from those. Reviewers do not ask for a changelog entry. +### Debugging -The mechanism stays for when the pause ends: an entry is one file, `changes/unreleased/.md`, and `bun run changelog` folds the entries into `CHANGELOG.md`. The `verify:lint` changelog check still validates any entry that exists. +Symptoms and fixes for extraction failures: [`packages/extract/CLAUDE.md`](packages/extract/CLAUDE.md) § Debugging Quick-Ref. -### Code Hygiene Workflow +## Key Rules -End-of-work mutating cleanup at `scripts/hygiene/`. Never CI-invoked. See [`scripts/hygiene/AGENTS.md`](scripts/hygiene/AGENTS.md) for cascade architecture (Layers A/B/C/D/D1), verdicts, receipts schema, preconditions, and recovery semantics. Authoritative requirement surface: `openspec/specs/code-hygiene/spec.md`. +- **Tool pins.** Bun and Node versions are pinned in `.tool-versions` (CI reads it through `bun-version-file` and `node-version-file`); `.node-version` repeats the Node version for Cloudflare Workers Builds. `vp run` puts the Bun named by `packageManager` in `package.json` first on `PATH`, so keep `packageManager` equal to the Bun version in `.tool-versions`. Do not run `vp env`: `.tool-versions` is the only source of the Bun version. +- **bun, not npm.** Install and run packages with `bun` and `bunx`, never `npm` or `npx`. Run the tasks in `vite.config.ts` and the owner `verify` scripts with `vp run`. +- **No React resolve aliases.** Aliasing `react` or `react-dom` moves React to an absolute path outside the package, and Vite then bundles the original source instead of the transformed one, with no error or warning. Deduplicate React with workspace hoisting, `package.json` `overrides` or Vite's `resolve.dedupe`. +- **Extraction runs in production and in dev.** +- **Tiers fail loudly.** A tier never builds what it needs: it stops with the command to run. -## Legacy Packages +## Release Notes -`legacy/` holds archived packages preserved for reference only — never installed, built, or published. `packages/*` and `e2e/*` MUST NOT import from `legacy/*` (see § One-Way Dependency Rule). For the catalog of legacy packages, workspace exclusion mechanics, and archived openspec path references, see [`legacy/AGENTS.md`](legacy/AGENTS.md). +Release notes are written from pull request bodies: a user-visible or breaking change states its release note in its pull request body. -### RepoWise File Loop +## RepoWise File Loop - Treat one file as the unit of work. Collect its dead-code, health, risk, ownership, caller, and decision leads together before planning an edit. @@ -210,16 +178,11 @@ End-of-work mutating cleanup at `scripts/hygiene/`. Never CI-invoked. See [`scri - Close the file by rechecking the live diff and relevant RepoWise signals. Record one terse row in the ignored `.repowise/cockpit.md`; do not create an increment packet, journal entry, or proposal for ordinary remediation. -- Escalate to OpenSpec only for a durable public contract, architectural or - dependency decision, migration, or genuinely cross-cutting behavior change. ## Agent skills Read `~/.agents/project-configuration.md` before using Matt's engineering -skills, and `~/.agents/openspec.md` before OpenSpec work. Use the shared skills -in `~/.agents/skills/`. Resolve every `openspec/specs/`, `openspec/changes/`, -and `openspec/schemas/` reference from the root reported by -`openspec list --json`; implementation paths refer to this checkout. +skills. Use the shared skills in `~/.agents/skills/`. ### Issue tracker @@ -239,7 +202,7 @@ Five canonical triage roles, mapped to this repo's label strings in `docs/agents ### Domain docs -Multi-context: root `CONTEXT-MAP.md` + per-package `CONTEXT.md` and `docs/adr/`. See `docs/agents/domain.md`. +Multi-context: root `CONTEXT-MAP.md` + per-package `CONTEXT.md`. See `docs/agents/domain.md`. diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index 62716539e..000000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,865 +0,0 @@ -# Change Log - -All notable changes to this project will be documented in this file. -See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. - -A new entry goes in its own file under `changes/unreleased/`, not in this -file. `bun run changelog` folds those files into the Unreleased section -below. AGENTS.md § Changelog Entries has the format. - -## Unreleased - -**Nested namespaces keep their CSS.** A module that re-exports another as a -namespace, with `export * as forms from './forms'` or -`import * as forms from './forms'; export { forms }`, made its components -reachable through the outer namespace without usage tracking seeing them. -``, `createElement(ui.forms.Input, …)` and a -clone of `` now count for `Input`, at any depth and -through a named import of the namespace, and so does a compose family's slot -such as ``. A value use such as -`Object.values(ui)` or `Object.values(ui.forms)` keeps every option of every -component the nested namespaces export. - -**Namespace objects passed as values keep their CSS.** A namespace import -used as a value, as in ``, `Object.values(ui)`, -`ui[name]` or `{ ...ui }`, can render any component the module exports, with -any props. Production builds used to keep only the options those components' -visible renders set. Every component the namespace's module exports, through -re-exports and barrels, now keeps every option it declares. Member renders -such as `` stay precise. - -**A skipped source no longer costs its components their CSS.** When a -non-strict build skips a source file, such as an MDX file that fails to -compile or whose `@mdx-js/mdx` peer is missing, or a configured source file -it cannot read, the analysis cannot see what it renders. Production builds -pruned the options only that file used: `` in a skipped MDX -file lost `lg`. While any file is skipped, nothing is pruned, so every -component, variant option and state is kept, and the skip warning now says -so. `strict` builds still fail on a skipped file. Every host now reports an -unreadable project or package file as -`animus.ingestion.unreadable-source-file`, which fails a `strict` build. -Before, the Vite plugin skipped a project file silently and a package file -with a plain warning, and the Next.js plugin and the CLI stopped on an -unreadable project file even without `strict`. - -**Namespace member renders keep their CSS.** With -`import * as ui from './components'`, a render such as `` -recorded nothing for `Button`, so when `Button` was also rendered directly, -production builds kept only the direct render's options and dropped `lg`. -Namespace member tags now resolve through the module's exports, re-exports -and `export *` barrels, and count like a direct render. The same applies to -`createElement(ui.Button, …)` and `cloneElement(, …)`. - -**Components loaded at runtime keep their CSS.** A component reached -through `import()`, `require()`, `require.context()`, -`import.meta.webpackContext()` or `import.meta.glob()` renders where usage -tracking cannot follow, as with `lazy(() => import('./button'))`, -`next/dynamic`, or `require('./button').Button`. Production builds used to -prune the variant and state options those renders set. Now every component -such a load can reach keeps every option it declares. That covers the loaded -module's exports, through re-exports, barrels and compose families, and -every analysed module a template literal, a concatenation, a context -directory or a glob can match. A specifier the analysis cannot read, such as -`require(name)`, reaches the modules in the importing file's directory and -below, which is all a bundler can load for it. Loads into packages outside -the analysis change nothing. - -**`cloneElement` overrides keep their CSS.** Production builds dropped the -variant and state options a `cloneElement` call sets: -`cloneElement( - ); -}; diff --git a/legacy/_docs/components/Highlighter/Highlighter.tsx b/legacy/_docs/components/Highlighter/Highlighter.tsx deleted file mode 100644 index 8a94cf8b4..000000000 --- a/legacy/_docs/components/Highlighter/Highlighter.tsx +++ /dev/null @@ -1,62 +0,0 @@ -import { Box } from '@animus-ui/components'; -import { animus } from '@animus-ui/core'; -import Highlight, { defaultProps } from 'prism-react-renderer'; - -import { usePrismTheme } from './usePrismTheme'; - -const Pre = animus - .styles({ - fontFamily: 'monospace', - p: 24, - fontSize: { _: 14, xs: 16 }, - position: 'relative', - }) - .system({ color: true, space: true, borders: true }) - .asElement('pre'); - -export const Line = animus.styles({ display: 'table-row' }).asElement('div'); - -export const Token = animus.styles({ transition: 'text' }).asElement('span'); - -export function Highlighter({ children }) { - const theme = usePrismTheme(); - return ( - - - {({ className, style, tokens, getLineProps, getTokenProps }) => ( -
-            {tokens.map((line, i) => {
-              const { key: lineKey, ...lineProps } = getLineProps({
-                line,
-                key: i,
-              });
-              return (
-                
-                  {line.map((token, key) => {
-                    const { tokenKey, ...tokenProps } = getTokenProps({
-                      token,
-                      key,
-                    });
-                    return ;
-                  })}
-                
-              );
-            })}
-          
- )} -
-
- ); -} diff --git a/legacy/_docs/components/Highlighter/usePrismTheme.ts b/legacy/_docs/components/Highlighter/usePrismTheme.ts deleted file mode 100644 index 76e3bab9c..000000000 --- a/legacy/_docs/components/Highlighter/usePrismTheme.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { PrismTheme } from 'prism-react-renderer'; -import { useMemo } from 'react'; - -import { theme } from '~theme'; - -const { colors } = theme; - -export const usePrismTheme = () => { - return useMemo( - () => ({ - plain: { - color: colors['syntax-text'], - }, - styles: [ - { - types: ['namespace', 'comment', 'prolog', 'doctype', 'cdata'], - style: { - opacity: 0.8, - }, - }, - { - types: ['number', 'boolean'], - style: { - color: colors['syntax-number'], - }, - }, - { - types: ['property', 'function', 'attr-name'], - style: { - color: colors['syntax-property'], - }, - }, - { - types: ['attr-value', 'string'], - style: { - color: colors['syntax-value'], - }, - }, - { - types: [ - 'keyword', - 'tag', - 'variable', - 'operator', - 'tag-id', - 'selector', - 'atrule-id', - ], - style: { - color: colors['syntax-keyword'], - }, - }, - { - types: [ - 'entity', - 'url', - 'control', - 'directive', - 'unit', - 'statement', - 'regex', - 'at-rule', - 'placeholder', - ], - style: { - color: colors['syntax-unit'], - }, - }, - { - types: ['deleted'], - style: { - textDecorationLine: 'line-through', - }, - }, - { - types: ['inserted'], - style: { - textDecorationLine: 'underline', - }, - }, - { - types: ['italic'], - style: { - fontStyle: 'italic', - }, - }, - { - types: ['important', 'bold'], - style: { - fontWeight: 'bold', - }, - }, - { - types: ['important'], - style: { - color: colors['syntax-important'], - }, - }, - ], - }), - [] - ); -}; diff --git a/legacy/_docs/components/Layout/Layout.tsx b/legacy/_docs/components/Layout/Layout.tsx deleted file mode 100644 index a690cc3ce..000000000 --- a/legacy/_docs/components/Layout/Layout.tsx +++ /dev/null @@ -1,113 +0,0 @@ -import { animus } from '@animus-ui/core'; - -const LayoutContainer = animus - .styles({ - position: 'relative', - zIndex: 1, - overflow: 'hidden', - bg: 'background', - minHeight: '100vh', - width: 1, - display: 'grid', - cols: '15rem:1', - rows: 'max:1', - gridTemplateAreas: '"header header" "content content"', - color: 'text', - fontFamily: 'base', - opacity: 1, - fontSize: { _: 16, xs: 18 }, - '&:before': { - zIndex: 0, - content: '""', - gradient: 'flowX', - backgroundSize: '500px 100%', - position: 'absolute', - width: '300vmax', - height: '300vh', - left: 0.5, - top: 0.5, - transformOrigin: '50% 50%', - transform: 'translate(-50%, -50%) rotate(45deg)', - }, - }) - .states({ - loading: { - opacity: 0, - }, - sidebar: { - gap: 2, - gridTemplateAreas: { - _: '"header header" "content content"', - sm: '"header header" "sidebar content"', - }, - height: '100vh', - }, - }) - .asElement('div'); - -const ContentContainer = animus - .styles({ - maxHeight: 1, - maxWidth: 1, - size: 1, - pt: { _: 24, sm: 48 }, - pb: 96, - px: { _: 24, sm: 64, xl: 96 }, - overflow: 'auto', - position: 'relative', - zIndex: 1, - area: 'content', - bg: 'background.current', - }) - .asElement('div'); - -const HeaderContainer = animus - .styles({ - width: 1, - display: 'flex', - justifyContent: 'center', - position: 'sticky', - top: 0, - bg: 'background', - height: '3.5rem', - area: 'header', - overflow: 'hidden', - py: 4, - px: { _: 16, sm: 32 }, - zIndex: 2, - }) - .asElement('div'); - -export const SidebarContainer = animus - .styles({ - bg: 'background.current', - area: 'sidebar', - height: 1, - top: '4rem', - maxHeight: 'calc(100vh - 3.5rem)', - overflowY: 'auto', - zIndex: 3, - position: { - _: 'absolute', - sm: 'static', - }, - right: 1, - '::-webkit-scrollbar': { - display: 'none', - }, - }) - .asElement('div'); - -type LayoutContainer = typeof LayoutContainer; - -export interface Layout extends LayoutContainer { - Content: typeof ContentContainer; - Header: typeof HeaderContainer; - Sidebar: typeof SidebarContainer; -} - -export const Layout = LayoutContainer as Layout; - -Layout.Content = ContentContainer; -Layout.Sidebar = SidebarContainer; -Layout.Header = HeaderContainer; diff --git a/legacy/_docs/components/Logo/Logo.tsx b/legacy/_docs/components/Logo/Logo.tsx deleted file mode 100644 index a144f7bd8..000000000 --- a/legacy/_docs/components/Logo/Logo.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import { animus } from '@animus-ui/core'; - -import { flow } from '../../animations/flow'; - -export const Logo = animus - .styles({ - width: 'max-content', - fontSize: 30, - m: 0, - lineHeight: 'initial', - fontFamily: 'logo', - letterSpacing: '2px', - gradient: 'flowX', - backgroundSize: '300px 100px', - animation: ` ${flow} 5s linear infinite`, - backgroundClip: 'text', - WebkitTextFillColor: 'transparent', - textShadow: 'logo', - transition: 'text', - }) - .states({ - link: { - animation: 'none', - '&:hover': { - textShadow: 'logo-hover', - animation: ` ${flow} 5s linear infinite`, - }, - '&:active': { - textShadow: 'link-pressed', - }, - }, - }) - .system({ typography: true }) - .props({ - logoSize: { - property: 'fontSize', - scale: { xs: 28, sm: 32, md: 64, lg: 72, xl: 96, xxl: 128 }, - }, - }) - .asElement('h1'); diff --git a/legacy/_docs/components/Meta.tsx b/legacy/_docs/components/Meta.tsx deleted file mode 100644 index 8819b17eb..000000000 --- a/legacy/_docs/components/Meta.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import Head from 'next/head'; -import React from 'react'; - -export interface MetaProps { - title?: string; - description?: string; -} - -export const Meta = ({ - title, - description = 'A configuration driven API for creating articulate component languages and expressive UIs.', -}: MetaProps) => { - const titleText = title ? `Animus | ${title}` : 'Animus '; - return ( - - {titleText} - - - ); -}; diff --git a/legacy/_docs/components/Sidebar/Sidebar.tsx b/legacy/_docs/components/Sidebar/Sidebar.tsx deleted file mode 100644 index d5cd62908..000000000 --- a/legacy/_docs/components/Sidebar/Sidebar.tsx +++ /dev/null @@ -1,57 +0,0 @@ -import { animus } from '@animus-ui/core'; -import { FlowLink } from 'elements/FlowLink'; -import { useRouter } from 'next/dist/client/router'; - -const LINKS = [ - { text: 'Introduction', href: '/start' }, - { text: 'Configure', href: '/configure' }, - { text: 'Properties', href: '/properties' }, - { text: 'Variants', href: '/variants' }, - { text: 'States', href: '/states' }, - { text: 'Components', href: '/component' }, - { text: 'Styling Philosophy', href: '/styling' }, - { text: 'Responsive', href: '/responsive' }, - { text: 'Theming', href: '/theming' }, -]; - -const Menu = animus - .styles({ - p: 32, - py: 12, - listStyleType: 'none', - }) - .states({ - submenu: { - px: 0, - pt: 8, - pb: 12, - }, - }) - .asElement('ul'); - -const MenuItem = animus - .styles({ - p: 4, - fontSize: 18, - lineHeight: 'base', - }) - .asElement('li'); - -export const Sidebar: React.FC = () => { - const { asPath } = useRouter(); - return ( - - {LINKS.map(({ text, href }) => { - const url = `/docs${href}`; - const isActive = asPath === url; - return ( - - - {text} - - - ); - })} - - ); -}; diff --git a/legacy/_docs/components/Tables.tsx b/legacy/_docs/components/Tables.tsx deleted file mode 100644 index 01e2e4be7..000000000 --- a/legacy/_docs/components/Tables.tsx +++ /dev/null @@ -1,107 +0,0 @@ -import { Text } from '@animus-ui/components'; -import { animus, compatTheme } from '@animus-ui/core'; -import { Prop } from '@animus-ui/core/dist/types/config'; -import { isArray, kebabCase, uniq } from 'lodash'; -import { Fragment, useMemo } from 'react'; - -import { Code } from '../elements/Code'; -import { Table } from '../elements/Tables'; - -export const PropTable = ({ - group, -}: { - group: keyof (typeof animus)['groupRegistry']; -}) => { - return ( - - - Prop - Properties - Scale - - {animus.groupRegistry[group].map((prop) => { - const { - property, - properties = [property], - scale, - } = animus.propRegistry[prop] as Prop; - const displayScaleValue = () => { - if (!scale) return null; - if (isArray(scale) && scale.length === 0) return 'Type Restricted'; - if (typeof scale === 'object') return JSON.stringify(scale); - return String(scale); - }; - - const scaleValue = displayScaleValue(); - return ( - - - {prop} - - - {properties.map(kebabCase).map((pn, i, arr) => ( - - - {pn} - - {arr.length !== i + 1 ? ', ' : ''} - - ))} - - - {scaleValue && {displayScaleValue()}} - - - ); - })} -
- ); -}; - -export const ScaleTable = () => { - const propertiesByScale = useMemo(() => { - const values = Object.keys(compatTheme).filter( - (key) => !['breakpoints', 'mode', 'modes'].includes(key) - ); - const props = Object.values(animus.propRegistry); - return values.map((scaleKey) => { - const properties = uniq( - props.reduce((carry, config: Prop) => { - if (config.scale !== scaleKey) return carry; - const propertyNames = config.properties - ? [...config.properties, config.property] - : [config.property]; - return carry.concat(propertyNames); - }, []) - ); - return { scale: scaleKey, properties }; - }); - }, []); - return ( - - - Scale - Properties - - {propertiesByScale.map(({ scale, properties }) => { - return ( - - - {scale} - - - {properties.map(kebabCase).map((pn, i, arr) => ( - - - {pn} - - {arr.length !== i + 1 ? ', ' : ''} - - ))} - - - ); - })} -
- ); -}; diff --git a/legacy/_docs/components/ThemeControl.tsx b/legacy/_docs/components/ThemeControl.tsx deleted file mode 100644 index 9a162c003..000000000 --- a/legacy/_docs/components/ThemeControl.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { AnimusProvider, ColorModes } from '@animus-ui/components'; -import { EmotionCache } from '@emotion/react'; -import Head from 'next/head'; -import { createContext, PropsWithChildren, useState } from 'react'; - -import { theme } from '~theme'; - -export const ThemeControlContext = createContext<{ - onChangeMode?: (mode: ColorModes) => void; -}>({}); - -export const ThemeControl: React.FC< - PropsWithChildren<{ cache: EmotionCache }> -> = ({ children, cache }) => { - const [mode, setMode] = useState('light'); - - return ( - - - - - - {children} - - - ); -}; diff --git a/legacy/_docs/elements/Button.tsx b/legacy/_docs/elements/Button.tsx deleted file mode 100644 index c0d1c4bb8..000000000 --- a/legacy/_docs/elements/Button.tsx +++ /dev/null @@ -1,129 +0,0 @@ -import { Arg, animus } from '@animus-ui/core'; - -export const ButtonContainer = animus - .styles({ - p: 0, - display: 'inline-flex', - alignItems: 'center', - justifyContent: 'center', - border: 'none', - borderRadius: 4, - boxShadow: 'none', - fontWeight: 700, - lineHeight: 'title', - letterSpacing: '1px', - cursor: 'pointer', - position: 'relative', - userSelect: 'none', - }) - .variant({ - variants: { - fill: { - color: 'background', - transition: 'bg', - bg: 'transparent', - gradient: 'flowX', - backgroundSize: '300px 100%', - backgroundPosition: '0% 0%', - '&:hover': { - backgroundPosition: '-100px 0%', - }, - '&:active:hover': { - backgroundPosition: '-400px 0%', - }, - }, - stroke: { - '&:before': { - content: '""', - position: 'absolute', - borderRadius: 4, - gradient: 'flowX', - backgroundSize: '300px 100px', - backgroundPosition: '0px 0%', - transition: 'bg', - inset: 0, - bg: 'background.current', - zIndex: 0, - }, - '&:after': { - content: '""', - inset: 2, - borderRadius: 2, - bg: 'background.current', - zIndex: 0, - position: 'absolute', - }, - '&:hover:before': { - backgroundPosition: '-100px 0%', - }, - '&:active:hover:before': { - backgroundPosition: '-400px 0%', - }, - }, - }, - }) - .asElement('button'); - -const ButtonForeground = animus - .variant({ - prop: 'size', - variants: { - sm: { - fontSize: 14, - lineHeight: '26px', - px: 8, - pb: 2, - minHeight: 28, - minWidth: 60, - }, - lg: { - fontSize: 22, - lineHeight: '48px', - px: 32, - pb: 2, - minHeight: 48, - minWidth: 100, - }, - }, - }) - .variant({ - variants: { - fill: {}, - stroke: { - userSelect: 'none', - position: 'relative', - zIndex: 1, - size: 1, - display: 'inline-block', - flex: 1, - transition: 'bg', - gradient: 'flowX', - backgroundSize: '300px 100px', - backgroundPosition: '0px 0%', - backgroundClip: 'text', - WebkitTextFillColor: 'transparent', - '&:hover': { - backgroundPosition: '-100px 0%', - }, - '&:active:hover': { - backgroundPosition: '-400px 0%', - }, - }, - }, - }) - .asElement('span'); - -export const Button = ({ - children, - variant = 'fill', - size = 'sm', - ...rest -}: Arg & Arg) => { - return ( - - - {children} - - - ); -}; diff --git a/legacy/_docs/elements/Code.tsx b/legacy/_docs/elements/Code.tsx deleted file mode 100644 index 168cd4ebb..000000000 --- a/legacy/_docs/elements/Code.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import { Box } from '@animus-ui/components'; -import { ComponentProps } from 'react'; - -export const Code = (props: ComponentProps) => ( - -); diff --git a/legacy/_docs/elements/FlowLink.tsx b/legacy/_docs/elements/FlowLink.tsx deleted file mode 100644 index 1b7c89459..000000000 --- a/legacy/_docs/elements/FlowLink.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import { Link } from '@animus-ui/components'; -import { animus } from '@animus-ui/core'; - -export const FlowLink = animus - .styles({ - fontWeight: 400, - gradient: 'flowX', - backgroundSize: '100px', - backgroundClip: 'text', - WebkitTextFillColor: 'transparent', - transition: 'text', - textShadow: 'flush', - fontFamily: 'base', - letterSpacing: '0.5px', - position: 'relative', - top: '2px', - '&:hover': { - fontWeight: 700, - textShadow: 'link-hover', - }, - '&:active': { - textShadow: 'link-pressed', - }, - }) - .states({ - raised: { - fontWeight: 700, - textShadow: 'link-raised', - '&:hover': { - textShadow: 'link-hover-raised', - }, - }, - active: { - fontWeight: 700, - textShadow: 'link-raised', - }, - }) - .asComponent(Link); diff --git a/legacy/_docs/elements/FlowText.tsx b/legacy/_docs/elements/FlowText.tsx deleted file mode 100644 index 2c023844b..000000000 --- a/legacy/_docs/elements/FlowText.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import { animus } from '@animus-ui/core'; - -import { flow } from '../animations/flow'; - -export const FlowText = animus - .styles({ - fontSize: 18, - fontWeight: 500, - letterSpacing: '1px', - bg: 'transparent', - gradient: 'flowX', - backgroundSize: '300px 100px', - backgroundClip: 'text', - WebkitTextFillColor: 'transparent', - textShadow: 'link-raised', - position: 'relative', - top: '2px', - }) - .states({ - flat: { - letterSpacing: '0px', - textShadow: 'flush', - }, - bare: { - top: '0px', - fontSize: 'inherit', - textShadow: 'none', - animation: `${flow} 5s linear 1s infinite`, - display: 'inline-block', - }, - }) - .system({ typography: true, layout: true, space: true }) - .asElement('div'); diff --git a/legacy/_docs/elements/Tables.tsx b/legacy/_docs/elements/Tables.tsx deleted file mode 100644 index a968afd2b..000000000 --- a/legacy/_docs/elements/Tables.tsx +++ /dev/null @@ -1,53 +0,0 @@ -import { animus } from '@animus-ui/core'; - -const TableBase = animus - .styles({ - mt: 16, - mb: 24, - fontSize: 14, - display: 'grid', - maxWidth: 1200, - width: 1, - }) - .asElement('div'); - -const TableRow = animus - .styles({ - display: 'flex', - px: 16, - '&:nth-child(even)': { - bg: 'syntax-background', - }, - }) - .states({ - header: { - border: 'none', - bg: 'transparent', - }, - }) - .asElement('div'); - -const TableCell = animus - .styles({ - py: 12, - flexBasis: '350px', - }) - .states({ - max: { - flexBasis: '150px', - }, - fill: { - flex: 1, - }, - }) - .props({ - size: { - property: 'flexBasis', - scale: { xs: '10rem', sm: '15rem' }, - }, - }) - .asElement('div'); - -const Table = Object.assign(TableBase, { Cell: TableCell, Row: TableRow }); - -export { Table }; diff --git a/legacy/_docs/fonts.ts b/legacy/_docs/fonts.ts deleted file mode 100644 index af5cdcacb..000000000 --- a/legacy/_docs/fonts.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { - Cairo, - DM_Mono, - Major_Mono_Display, - Space_Mono, -} from 'next/font/google'; - -export const Logo = Major_Mono_Display({ - weight: '400', - style: 'normal', - subsets: ['latin'], -}); - -export const Body = Cairo({ - weight: ['400', '600', '700'], - style: 'normal', - subsets: ['latin'], -}); - -export const Heading = Space_Mono({ - weight: ['400', '700'], - style: ['normal'], - subsets: ['latin'], -}); - -export const Mono = DM_Mono({ - style: ['normal', 'italic'], - weight: '400', - subsets: ['latin'], -}); diff --git a/legacy/_docs/hooks/useDeferredRender.ts b/legacy/_docs/hooks/useDeferredRender.ts deleted file mode 100644 index 0fe992739..000000000 --- a/legacy/_docs/hooks/useDeferredRender.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { useState } from 'react'; - -import { useIsomorphicLayoutEffect } from './useIsomorphicLayoutEffect'; - -export const useDeferredRender = () => { - const [ready, setReady] = useState(false); - useIsomorphicLayoutEffect(() => { - setReady(true); - }, []); - return ready; -}; diff --git a/legacy/_docs/hooks/useIsomorphicLayoutEffect.ts b/legacy/_docs/hooks/useIsomorphicLayoutEffect.ts deleted file mode 100644 index ebee7f282..000000000 --- a/legacy/_docs/hooks/useIsomorphicLayoutEffect.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { useEffect, useLayoutEffect } from 'react'; - -export const useIsomorphicLayoutEffect = - typeof window !== 'undefined' ? useLayoutEffect : useEffect; diff --git a/legacy/_docs/next-env.d.ts b/legacy/_docs/next-env.d.ts deleted file mode 100644 index a4a7b3f5c..000000000 --- a/legacy/_docs/next-env.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -/// -/// - -// NOTE: This file should not be edited -// see https://nextjs.org/docs/pages/building-your-application/configuring/typescript for more information. diff --git a/legacy/_docs/pages/_app.tsx b/legacy/_docs/pages/_app.tsx deleted file mode 100644 index 66cfca3b3..000000000 --- a/legacy/_docs/pages/_app.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import { useRouter } from 'next/dist/client/router'; - -import { AppWrapper } from '../components/AppProvider/AppWrapper'; -import { Header } from '../components/Header/Header'; -import { Layout } from '../components/Layout/Layout'; -import { Meta } from '../components/Meta'; -import { Sidebar } from '../components/Sidebar/Sidebar'; - -const App = ({ Component, pageProps, cache }: any) => { - const { asPath } = useRouter(); - const isDocsPage = asPath !== '/'; - - return ( - - - - -
- - {isDocsPage && ( - - - - )} - - - - - - ); -}; - -export default App; diff --git a/legacy/_docs/pages/_document.tsx b/legacy/_docs/pages/_document.tsx deleted file mode 100644 index 32d5b0d99..000000000 --- a/legacy/_docs/pages/_document.tsx +++ /dev/null @@ -1,59 +0,0 @@ -import createCache from '@emotion/cache'; -import createEmotionServer from '@emotion/server/create-instance'; -import Document, { - DocumentContext, - Head, - Html, - Main, - NextScript, -} from 'next/document'; -import React, { ReactElement } from 'react'; - -class MyDocument extends Document { - static async getInitialProps(ctx: DocumentContext) { - const originalRenderPage = ctx.renderPage; - - const cache = createCache({ key: 'animus' }); - // eslint-disable-next-line @typescript-eslint/unbound-method - const { extractCriticalToChunks } = createEmotionServer(cache); - - ctx.renderPage = () => - originalRenderPage({ - enhanceApp: (App) => (props) => ( - - ), - }); - - const initialProps = await Document.getInitialProps(ctx); - const emotionStyles = extractCriticalToChunks(initialProps.html); - const emotionStyleTags = emotionStyles.styles.map((style) => ( - `; - expect(() => assertBootstrapScriptFirst(trailing)).toThrow(AssertionError); - }); - - it('refuses to pass on a document with no stylesheet reference at all', () => { - const noCss = ``; - expect(() => assertBootstrapScriptFirst(noCss)).toThrow(AssertionError); - }); - - it('rejects a document with no bootstrap script', () => { - expect(() => - assertBootstrapScriptFirst( - '' - ) - ).toThrow(AssertionError); - }); -}); - -describe('assertCharsetWithinByteBudget', () => { - it('accepts a charset declaration inside the byte budget', () => { - expect(() => - assertCharsetWithinByteBudget(NEXT_APP_LEGACY_PAGE_HTML_ARTIFACT) - ).not.toThrow(); - }); - - it('rejects a declaration pushed past the budget', () => { - const padded = ``; - expect(() => assertCharsetWithinByteBudget(padded)).toThrow(AssertionError); - }); - - it('measures bytes, not UTF-16 code units', () => { - const padded = ``; - expect(padded.indexOf('/>')).toBeLessThanOrEqual(1024); - expect(() => assertCharsetWithinByteBudget(padded)).toThrow(AssertionError); - }); - - it('fails loud when no encoding declaration exists at all', () => { - expect(() => - assertCharsetWithinByteBudget('') - ).toThrow(AssertionError); - }); -}); - -describe('assertNoBootstrapScript', () => { - it('passes on a document the application never touched', () => { - expect(() => - assertNoBootstrapScript( - '' - ) - ).not.toThrow(); - }); - - it('fails as soon as the marker appears', () => { - expect(() => - assertNoBootstrapScript(NEXT_APP_LEGACY_PAGE_HTML_ARTIFACT) - ).toThrow(AssertionError); - }); -}); diff --git a/packages/_assertions/__tests__/assert-css.test.ts b/packages/_assertions/__tests__/assert-css.test.ts deleted file mode 100644 index d0c8c8619..000000000 --- a/packages/_assertions/__tests__/assert-css.test.ts +++ /dev/null @@ -1,352 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { - AssertionError, - assertClassNameFormat, - assertKeyframesExtracted, - assertLayerOrder, - assertNoDevDiagnostics, - assertNoEmotionImports, - assertNoPlaceholders, - assertNoUnresolvedTokens, - assertVariantDeclarationParity, - layerBlockBody, -} from '../src/assert-css'; - -const ORDERED_CSS = ` -@layer anm-global, anm-base, anm-variants; -:root { - --colors-primary: #abc; -} -@layer anm-global { html { box-sizing: border-box; } } -@layer anm-base { .animus-card { padding: 8px; } } -@layer anm-variants { .animus-card--primary { color: red; } } -`.trim(); - -describe('assertLayerOrder', () => { - it('passes for correctly ordered CSS', () => { - expect(() => assertLayerOrder(ORDERED_CSS)).not.toThrow(); - }); - - it('fails when :root appears after a layer block', () => { - const broken = - '@layer anm-global, anm-base, anm-variants; @layer anm-base { .x {} } :root { --c: red; } @layer anm-global {} @layer anm-variants {}'; - expect(() => assertLayerOrder(broken)).toThrow(AssertionError); - }); - - it('fails when an expected layer is missing', () => { - const missing = - '@layer anm-global, anm-base; :root {} @layer anm-global {} @layer anm-base {}'; - expect(() => assertLayerOrder(missing)).toThrow(/anm-variants/); - }); - - it('honors a custom layer list', () => { - const css = '@layer x; :root {} @layer x {}'; - expect(() => - assertLayerOrder(css, { layers: ['@layer ', ':root', '@layer x {'] }) - ).not.toThrow(); - }); - - it('accepts regex markers including minified (no-space) layer blocks', async () => { - const { layerBlock } = await import('../src/assert-css'); - const minified = - '@layer anm-base,anm-variants;@layer anm-base{.x{}}@layer anm-variants{.y{}}'; - expect(() => - assertLayerOrder(minified, { - layers: [layerBlock('anm-base'), layerBlock('anm-variants')], - }) - ).not.toThrow(); - }); - - it('names a missing string marker verbatim and a missing regex marker as a pattern', () => { - expect(() => - assertLayerOrder('/* empty */', { layers: ['@layer anm-base {'] }) - ).toThrow('missing expected layer markers: @layer anm-base {'); - expect(() => - assertLayerOrder('/* empty */', { layers: [/@layer\s+anm-base/] }) - ).toThrow('missing expected layer markers: /@layer\\s+anm-base/'); - }); -}); - -describe('assertNoPlaceholders', () => { - it('passes for clean CSS', () => { - expect(() => assertNoPlaceholders(ORDERED_CSS)).not.toThrow(); - }); - - it('fails when __TRANSFORM__ is present', () => { - expect(() => assertNoPlaceholders('.x { color: __TRANSFORM__; }')).toThrow( - AssertionError - ); - }); -}); - -describe('assertClassNameFormat', () => { - it('passes when prefix is present', () => { - expect(() => assertClassNameFormat('.animus-button {}')).not.toThrow(); - }); - - it('fails when prefix is absent', () => { - expect(() => assertClassNameFormat('.foo {}')).toThrow(AssertionError); - }); - - it('honors custom prefix', () => { - expect(() => - assertClassNameFormat('.anm-x {}', { prefix: 'anm-' }) - ).not.toThrow(); - }); -}); - -describe('assertNoUnresolvedTokens', () => { - it('passes when no unresolved tokens are present', () => { - expect(() => - assertNoUnresolvedTokens('.x { color: var(--colors-primary); }') - ).not.toThrow(); - }); - - it('fails when {colors.primary} appears unresolved', () => { - expect(() => - assertNoUnresolvedTokens('.x { color: {colors.primary}; }') - ).toThrow(AssertionError); - }); - - it('honors custom forbidden patterns', () => { - expect(() => - assertNoUnresolvedTokens('.x { z-index: {z.primary}; }', { - forbiddenPatterns: [/\{z\.[a-zA-Z][\w.-]*\}/], - }) - ).toThrow(AssertionError); - }); -}); - -describe('assertNoEmotionImports', () => { - it('passes for clean JS', () => { - expect(() => - assertNoEmotionImports("import { render } from 'react-dom';") - ).not.toThrow(); - }); - - it('fails when @emotion import is present', () => { - expect(() => - assertNoEmotionImports("import x from '@emotion/css';") - ).toThrow(AssertionError); - }); -}); - -describe('assertNoDevDiagnostics', () => { - it('passes for a folded production bundle', () => { - expect(() => - assertNoDevDiagnostics('const a=1;console.log(a);') - ).not.toThrow(); - }); - - it('fails when the drop-diagnostic marker survived the fold', () => { - expect(() => - assertNoDevDiagnostics('console.warn("[animus:drop] Card: value 8");') - ).toThrow(AssertionError); - }); - - it('honors a custom marker', () => { - expect(() => - assertNoDevDiagnostics( - 'const w=__ANIMUS_WITNESS__;', - '__ANIMUS_WITNESS__' - ) - ).toThrow(AssertionError); - }); -}); - -describe('assertKeyframesExtracted', () => { - const GOOD_CSS = ` - @layer anm-global { - @keyframes animus-kf-abc { 0% { opacity: 0 } 100% { opacity: 1 } } - @keyframes animus-kf-def { 0% { transform: scale(1) } 50% { transform: scale(1.1) } } - } - .animus-x { animation-name: animus-kf-abc } - .animus-y { animation-name: animus-kf-def } - `; - - it('passes for well-formed keyframes CSS', () => { - expect(() => - assertKeyframesExtracted(GOOD_CSS, { - minBlocks: 2, - minReferences: 2, - insideLayer: 'anm-global', - }) - ).not.toThrow(); - }); - - it('fails when no @keyframes blocks are present', () => { - const css = '.x { animation-name: animus-kf-xyz }'; - expect(() => assertKeyframesExtracted(css)).toThrow( - /expected at least 1 @keyframes block/ - ); - }); - - it('fails when no prefixed animation-name references are present', () => { - const css = '@keyframes animus-kf-abc { 0% {} }'; - expect(() => assertKeyframesExtracted(css)).toThrow( - /expected at least 1 animation-name reference/ - ); - }); - - it('fails when a reference has no matching @keyframes block', () => { - const css = - '@keyframes animus-kf-abc { 0% {} } .x { animation-name: animus-kf-xyz }'; - expect(() => assertKeyframesExtracted(css)).toThrow( - /no matching @keyframes block: animus-kf-xyz/ - ); - }); - - it('fails when unit-fallback mangles the identifier with trailing px', () => { - const css = - '@keyframes animus-kf-1w7pb41 {} .x { animation-name: animus-kf-1w7pb41px }'; - expect(() => assertKeyframesExtracted(css)).toThrow(/trailing 'px'/); - }); - - it('skips CSS keyword values when counting references', () => { - const css = - '@keyframes animus-kf-abc {} .x { animation-name: animus-kf-abc } .y { animation-name: none } .z { animation-name: INHERIT }'; - expect(() => assertKeyframesExtracted(css)).not.toThrow(); - }); - - it('passes when a block is inside the expected @layer span', () => { - const css = - '@layer anm-global { @keyframes animus-kf-abc {} } .x { animation-name: animus-kf-abc }'; - expect(() => - assertKeyframesExtracted(css, { insideLayer: 'anm-global' }) - ).not.toThrow(); - }); - - it('fails when a block is outside the expected @layer span', () => { - const css = - '@keyframes animus-kf-abc {} @layer anm-global {} .x { animation-name: animus-kf-abc }'; - expect(() => - assertKeyframesExtracted(css, { insideLayer: 'anm-global' }) - ).toThrow(/outside @layer anm-global/); - }); - - it('fails when insideLayer block is entirely absent', () => { - const css = - '@keyframes animus-kf-abc {} .x { animation-name: animus-kf-abc }'; - expect(() => - assertKeyframesExtracted(css, { insideLayer: 'anm-global' }) - ).toThrow(/no @layer anm-global block was found/); - }); - - it('honors minBlocks threshold', () => { - const css = - '@keyframes animus-kf-abc {} .x { animation-name: animus-kf-abc }'; - expect(() => assertKeyframesExtracted(css, { minBlocks: 2 })).toThrow( - /expected at least 2/ - ); - }); - - it('honors custom namePrefix', () => { - const css = '@keyframes custom-abc {} .x { animation-name: custom-abc }'; - expect(() => - assertKeyframesExtracted(css, { namePrefix: 'custom-' }) - ).not.toThrow(); - expect(() => assertKeyframesExtracted(css)).toThrow( - /expected at least 1 @keyframes block/ - ); - }); - - it('tolerates multiple @layer anm-global blocks (chunk concatenation)', () => { - const css = - '@layer anm-global { @keyframes animus-kf-abc {} } @layer anm-global { @keyframes animus-kf-def {} } .x { animation-name: animus-kf-abc } .y { animation-name: animus-kf-def }'; - expect(() => - assertKeyframesExtracted(css, { - insideLayer: 'anm-global', - minBlocks: 2, - minReferences: 2, - }) - ).not.toThrow(); - }); - - it('accepts minified CSS (no whitespace around braces)', () => { - const css = - '@layer anm-global{@keyframes animus-kf-abc{0%{opacity:0}100%{opacity:1}}}.animus-x{animation-name:animus-kf-abc}'; - expect(() => - assertKeyframesExtracted(css, { insideLayer: 'anm-global' }) - ).not.toThrow(); - }); -}); - -describe('assertVariantDeclarationParity', () => { - const parityCss = ( - leftBase: string, - rightBase: string, - smLeft: string, - smRight: string - ) => - ` -.animus-Left-abc123 { ${leftBase} } -.animus-Right-def456 { ${rightBase} } -.animus-Left-abc123--size-sm { ${smLeft} } -.animus-Right-def456--size-sm { ${smRight} } -`.trim(); - - const config = { - components: ['Left', 'Right'] as const, - optionSuffixes: ['size-sm'], - }; - - it('passes when both siblings emit identical declarations in order', () => { - const css = parityCss( - 'margin: 0; margin-left: 1px', - 'margin: 0; margin-left: 1px', - 'padding: 4px', - 'padding: 4px' - ); - expect(() => assertVariantDeclarationParity(css, config)).not.toThrow(); - }); - - it('fails when equal declaration sets diverge in emitted order', () => { - const css = parityCss( - 'margin: 0; margin-left: 1px', - 'margin-left: 1px; margin: 0', - 'padding: 4px', - 'padding: 4px' - ); - expect(() => assertVariantDeclarationParity(css, config)).toThrow( - AssertionError - ); - }); - - it('fails on a declaration content mismatch', () => { - const css = parityCss( - 'margin: 0', - 'margin: 2px', - 'padding: 4px', - 'padding: 4px' - ); - expect(() => assertVariantDeclarationParity(css, config)).toThrow( - AssertionError - ); - }); -}); - -describe('layerBlockBody', () => { - it('returns the body of the named layer block', () => { - expect(layerBlockBody(ORDERED_CSS, 'anm-base')).toBe( - ' .animus-card { padding: 8px; } ' - ); - }); - - it('returns undefined when the sheet declares no such block', () => { - expect(layerBlockBody(ORDERED_CSS, 'anm-states')).toBeUndefined(); - }); - - it('brace-matches so a nested at-rule does not terminate the body early', () => { - const css = - '@layer anm-global { @media (min-width: 10px) { body { margin: 0; } } .tail { gap: 1px; } }'; - const body = layerBlockBody(css, 'anm-global'); - expect(body).toContain('.tail { gap: 1px; }'); - expect(body).toContain('@media'); - }); - - it('takes the FIRST block when a layer is reopened', () => { - const css = '@layer anm-base { a { x: 1 } } @layer anm-base { b { y: 2 } }'; - expect(layerBlockBody(css, 'anm-base')).toBe(' a { x: 1 } '); - }); -}); diff --git a/packages/_assertions/__tests__/conditions-inside-layers.test.ts b/packages/_assertions/__tests__/conditions-inside-layers.test.ts deleted file mode 100644 index 5f7c5412f..000000000 --- a/packages/_assertions/__tests__/conditions-inside-layers.test.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { - AssertionError, - assertConditionsInsideLayers, -} from '../src/assert-css'; - -const CONDITIONS_IN_LAYERS = ` -@layer anm-global, anm-base, anm-variants, anm-system; -:root { --color-primary: #abc; } -@layer anm-base { - .animus-Card-abcd1234 { - display: flex; - } - @media (min-width: 768px) { - .animus-Card-abcd1234 { - gap: 1rem; - } - } - @container card (min-width: 400px) { - .animus-Card-abcd1234 { - font-size: 18px; - } - } - @media (prefers-reduced-motion: reduce) { - .animus-Card-abcd1234 { - transition: none; - } - } - @supports (display: grid) { - .animus-Card-abcd1234 { - display: grid; - } - } -} -@layer anm-variants { - @layer standalone, composed; - @layer composed { - @container (min-width: 600px) { - .animus-Card-abcd1234--size-lg { padding: 2rem; } - } - } -} -`.trim(); - -describe('assertConditionsInsideLayers (Guardrail G2)', () => { - it('passes when every condition at-rule nests inside a named @layer block', () => { - expect(() => - assertConditionsInsideLayers(CONDITIONS_IN_LAYERS) - ).not.toThrow(); - }); - - it('fails when a @container rule appears outside any @layer block', () => { - const hoisted = ` -@layer anm-base { .animus-Card { display: flex; } } -@container (min-width: 400px) { .animus-Card { font-size: 18px; } } -`.trim(); - expect(() => assertConditionsInsideLayers(hoisted)).toThrow(AssertionError); - }); - - it('fails when a @supports rule is hoisted to the top level', () => { - const hoisted = ` -@supports (display: grid) { .animus-Card { display: grid; } } -@layer anm-base { .animus-Card { display: flex; } } -`.trim(); - expect(() => assertConditionsInsideLayers(hoisted)).toThrow(AssertionError); - }); - - it('fails when a non-breakpoint @media is outside a layer', () => { - const hoisted = ` -@layer anm-base { .animus-Card { color: red; } } -@media (prefers-reduced-motion: reduce) { .animus-Card { transition: none; } } -`.trim(); - expect(() => assertConditionsInsideLayers(hoisted)).toThrow(AssertionError); - }); - - it('is vacuously green on output with no condition at-rules', () => { - const plain = ` -@layer anm-base { .animus-Card { display: flex; padding: 8px; } } -`.trim(); - expect(() => assertConditionsInsideLayers(plain)).not.toThrow(); - }); - - it('reports the offending at-rule family and offset in the error', () => { - const hoisted = - '@layer anm-base { .x { color: red; } } @container (min-width: 400px) { .x { gap: 1rem; } }'; - try { - assertConditionsInsideLayers(hoisted); - throw new Error('expected assertion to throw'); - } catch (err) { - expect(err).toBeInstanceOf(AssertionError); - if (!(err instanceof AssertionError)) throw err; - expect(err.message).toContain('@container'); - expect(err.details).toHaveProperty('offenders'); - } - }); -}); diff --git a/packages/_assertions/__tests__/receipt.test.ts b/packages/_assertions/__tests__/receipt.test.ts deleted file mode 100644 index f005c256f..000000000 --- a/packages/_assertions/__tests__/receipt.test.ts +++ /dev/null @@ -1,162 +0,0 @@ -import { - existsSync, - mkdirSync, - mkdtempSync, - readFileSync, - rmSync, - writeFileSync, -} from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { afterEach, describe, expect, it } from 'vitest'; - -import { AssertionError } from '../src/assert-css'; -import { parseJsonObject } from '../src/json'; -import { installedHostVersion, writeLaneReceipt } from '../src/receipt'; - -const dirs: string[] = []; - -function scratchDir(): string { - const dir = mkdtempSync(join(tmpdir(), 'lane-receipt-')); - dirs.push(dir); - return dir; -} - -function cleanConfig(dir: string): string { - const path = join(dir, 'vite.config.ts'); - writeFileSync( - path, - "import { animusExtract } from '@animus-ui/vite-plugin';\n" + - "export default { plugins: [animusExtract({ system: './src/ds.ts' })] };\n" - ); - return path; -} - -afterEach(() => { - while (dirs.length > 0) { - const dir = dirs.pop(); - if (dir) rmSync(dir, { recursive: true, force: true }); - } -}); - -describe('writeLaneReceipt', () => { - it('round-trips all eight fields through JSON.parse', () => { - const dir = scratchDir(); - const path = join(dir, 'verify-assert-vite.json'); - - const returned = writeLaneReceipt(path, { - lane: 'verify:assert:vite', - host: 'vite', - hostVersion: '7.1.2', - mode: 'production', - packageForm: 'workspace', - engineConfigPath: cleanConfig(dir), - }); - - const parsed = parseJsonObject(readFileSync(path, 'utf8'), 'lane receipt'); - expect(parsed).toEqual(returned); - expect(parsed).toEqual({ - lane: 'verify:assert:vite', - host: 'vite', - hostVersion: '7.1.2', - mode: 'production', - engineLoaded: 'v2', - engineDefault: 'v2', - engineOverride: false, - packageForm: 'workspace', - }); - }); - - it('creates missing parent directories and appends a trailing newline', () => { - const dir = scratchDir(); - const path = join(dir, 'nested', '.receipts', 'verify-assert-next.json'); - - const returned = writeLaneReceipt(path, { - lane: 'verify:assert:next', - host: 'next', - hostVersion: '15.5.0', - mode: 'production', - packageForm: 'packed', - engineConfigPath: cleanConfig(dir), - }); - - const raw = readFileSync(path, 'utf8'); - expect(raw.endsWith('\n')).toBe(true); - expect(JSON.parse(raw)).toEqual(returned); - }); - - for (const [label, source] of [ - ['an explicit engine option', "animusExtract({ engine: 'v1' })"], - ['a spaced engine option', 'animusExtract({ engine : "v2" })'], - ['an ANIMUS_ENGINE reference', 'process.env.ANIMUS_ENGINE === "v1"'], - ] as const) { - it(`refuses to record engine identity when the config has ${label}`, () => { - const dir = scratchDir(); - const configPath = join(dir, 'vite.config.ts'); - writeFileSync(configPath, `export default { probe: ${source} };\n`); - const path = join(dir, '.receipts', 'verify-assert-vite.json'); - - expect(() => - writeLaneReceipt(path, { - lane: 'verify:assert:vite', - host: 'vite', - hostVersion: '7.1.2', - mode: 'production', - packageForm: 'workspace', - engineConfigPath: configPath, - }) - ).toThrow(AssertionError); - expect(existsSync(path)).toBe(false); - }); - } - - it('names the config in the failure, defaulting the label to its basename', () => { - const dir = scratchDir(); - const configPath = join(dir, 'next.config.ts'); - writeFileSync(configPath, "withAnimus({ engine: 'v1' });\n"); - - expect(() => - writeLaneReceipt(join(dir, 'receipt.json'), { - lane: 'verify:assert:next', - host: 'next', - hostVersion: '15.5.0', - mode: 'production', - packageForm: 'workspace', - engineConfigPath: configPath, - }) - ).toThrow(/^next\.config\.ts must not reference ANIMUS_ENGINE/); - - expect(() => - writeLaneReceipt(join(dir, 'receipt.json'), { - lane: 'verify:assert:next', - host: 'next', - hostVersion: '15.5.0', - mode: 'production', - packageForm: 'workspace', - engineConfigPath: configPath, - engineConfigLabel: 'packages/showcase/vite.config.ts', - }) - ).toThrow(/^packages\/showcase\/vite\.config\.ts must not reference/); - }); -}); - -describe('installedHostVersion', () => { - it('reads the version from the installed manifest, not a declared range', () => { - const root = scratchDir(); - mkdirSync(join(root, 'node_modules', 'vinext'), { recursive: true }); - writeFileSync( - join(root, 'node_modules', 'vinext', 'package.json'), - JSON.stringify({ name: 'vinext', version: '1.0.0-beta.1' }) - ); - writeFileSync( - join(root, 'package.json'), - JSON.stringify({ dependencies: { vinext: '^1.0.0' } }) - ); - - expect(installedHostVersion(root, 'vinext')).toBe('1.0.0-beta.1'); - }); - - it('throws when the host is not installed', () => { - expect(() => installedHostVersion(scratchDir(), 'vinext')).toThrow(); - }); -}); diff --git a/packages/_assertions/__tests__/served-client-css.test.ts b/packages/_assertions/__tests__/served-client-css.test.ts deleted file mode 100644 index ea69e0aa7..000000000 --- a/packages/_assertions/__tests__/served-client-css.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join, resolve } from 'node:path'; -import { afterEach, describe, expect, it } from 'vitest'; - -import { AssertionError } from '../src/assert-css'; -import { readRequiredCss } from '../src/find-build-assets'; - -const temporaryDirectories: string[] = []; - -function scaffold() { - const root = mkdtempSync(resolve(tmpdir(), 'animus-served-client-css-')); - temporaryDirectories.push(root); - const clientRoot = join(root, 'client'); - const serverRoot = join(root, 'server'); - mkdirSync(clientRoot, { recursive: true }); - mkdirSync(serverRoot, { recursive: true }); - return { root, clientRoot, serverRoot }; -} - -const SEMANTIC_CSS = `@layer anm-base, anm-variants; -:root { --color-text: #111; } -@layer anm-base { .animus-card { padding: 8px; } } -@layer anm-variants { .animus-card--primary { color: red; } } -`; - -afterEach(() => { - for (const directory of temporaryDirectories.splice(0)) { - rmSync(directory, { recursive: true, force: true }); - } -}); - -describe('readRequiredCss', () => { - it('throws naming served-client CSS when only server output has CSS', async () => { - const { clientRoot, serverRoot } = scaffold(); - // Valid CSS exists only under the server root; the client root is empty. - writeFileSync(join(serverRoot, 'server.css'), SEMANTIC_CSS); - - await expect( - readRequiredCss(clientRoot, 'vinext served-client CSS') - ).rejects.toThrow(AssertionError); - await expect( - readRequiredCss(clientRoot, 'vinext served-client CSS') - ).rejects.toThrow(/served-client/); - }); - - it('treats an empty CSS file under the client root as missing', async () => { - const { clientRoot } = scaffold(); - writeFileSync(join(clientRoot, 'empty.css'), ' \n'); - - await expect( - readRequiredCss(clientRoot, 'vinext served-client CSS') - ).rejects.toThrow(AssertionError); - }); - - it('returns only the client root CSS when it is non-empty', async () => { - const { clientRoot, serverRoot } = scaffold(); - mkdirSync(join(clientRoot, 'assets'), { recursive: true }); - writeFileSync(join(clientRoot, 'assets', 'styles.css'), SEMANTIC_CSS); - // Server CSS must never leak into the returned client CSS. - writeFileSync( - join(serverRoot, 'server.css'), - '.server-only { color: hotpink; }' - ); - - const css = await readRequiredCss(clientRoot, 'vinext served-client CSS'); - - expect(css).toContain('@layer anm-base'); - expect(css).toContain(':root'); - expect(css).toContain('animus-card'); - expect(css).not.toContain('server-only'); - }); -}); diff --git a/packages/_assertions/src/assert-appearance.ts b/packages/_assertions/src/assert-appearance.ts index b275b9d04..c9443aff5 100644 --- a/packages/_assertions/src/assert-appearance.ts +++ b/packages/_assertions/src/assert-appearance.ts @@ -1,7 +1,3 @@ -/** - * Runs over BUILT CSS: minifiers drop attribute-value quotes and Lightning CSS - * injects `--lightningcss-*` pairs into any rule declaring `color-scheme`. - */ import { AssertionError, compact } from './assert-css'; export type OsScheme = 'light' | 'dark'; @@ -33,10 +29,6 @@ interface Rule { index: number; } -/** - * Every style rule at any depth, with offsets into the original string. - * At-rules are descended into rather than returned. - */ function styleRules(css: string, offset = 0): Rule[] { const rules: Rule[] = []; let cursor = 0; @@ -87,8 +79,6 @@ function schemeBlocks(css: string): SchemeBlock[] { const close = matchBrace(css, open); if (close === -1) continue; blocks.push({ - // SAFETY: group 1 of `openRe` is a non-optional `(light|dark)` - // alternation, so a match carries one of the two `OsScheme` spellings. scheme: match[1] as OsScheme, index: match.index, rules: styleRules(css.slice(open + 1, close), open + 1), @@ -97,22 +87,12 @@ function schemeBlocks(css: string): SchemeBlock[] { return blocks; } -/** - * True when a comma-part of `selector` targets `:root`, the only root spelling - * the theme emitter writes; a bare `html` rule is the application's own. - */ function targetsRoot(selector: string): boolean { return selector .split(',') .some((part) => /(^|[\s>+~]):root\b/.test(part.trim())); } -/** - * The initial mode's attribute rule when it also carries the guard: the theme - * emitter folds that mode's system-preference block into it, so it is the - * fallback for the scheme no media block covers, and must precede the media - * block that covers the other. - */ function foldedFallback( css: string, guard = DEFAULT_GUARD @@ -137,23 +117,16 @@ function foldedFallback( return undefined; } -/** A scheme block's rules that carry exactly the guard. */ function guardedRules(block: SchemeBlock, guard = DEFAULT_GUARD): Rule[] { return block.rules.filter((rule) => compact(rule.prelude) === compact(guard)); } -/** The custom properties a rule body declares, by name. */ function customProperties(body: string): string[] { return declarationList(body) .filter((declaration) => declaration.startsWith('--')) .map((declaration) => declaration.split(':')[0].trim()); } -/** The folded fallback, when it serves `scheme`: no guarded media block - * covers `scheme`, and the other scheme's guarded block follows the fold and - * declares every custom property it does, so it overrides each one under - * the other preference. A component's own scheme conditions are not - * fallbacks. */ function foldedFallbackFor( css: string, scheme: OsScheme, @@ -190,10 +163,6 @@ function modeRule(css: string, mode: string): Rule | undefined { return styleRules(css).find((rule) => re.test(rule.prelude)); } -/** - * Spans of the theme's unlayered `prefers-color-scheme` fallback blocks, which - * sit beside `:root` so variable resolution stays out of the layer order. - */ export function systemSchemeVariableSpans(css: string): [number, number][] { const firstLayerBlock = css.match(/@layer\s+[\w-]+\s*\{/)?.index ?? -1; @@ -212,8 +181,6 @@ export function systemSchemeVariableSpans(css: string): [number, number][] { const close = matchBrace(css, open); if (open === -1 || close === -1) continue; - // A nested at-rule forfeits the exemption: the span would otherwise grant - // it blanket cover from the containment gate. if (/@[a-zA-Z-]/.test(css.slice(open + 1, close))) continue; spans.push([block.index, close]); @@ -222,18 +189,10 @@ export function systemSchemeVariableSpans(css: string): [number, number][] { } export interface SystemSchemeGuardConfig { - /** - * OS schemes that must appear as guarded root blocks assigning at least one - * custom property. Omitting it leaves the presence check unarmed. - */ expectSchemes?: readonly OsScheme[]; guard?: string; } -/** - * Every ROOT-targeting rule inside a `prefers-color-scheme` block carries the - * guard, so the fallback never fights an explicit mode; other rules are free. - */ export function assertSystemSchemeGuard( css: string, config?: SystemSchemeGuardConfig @@ -294,10 +253,6 @@ export interface ColorSchemeEmissionConfig { system?: Readonly>>; } -/** - * `color-scheme` is emitted on `:root`, on every declared mode's attribute - * block, and inside each guarded media block, so native surfaces track it. - */ export function assertColorSchemeEmission( css: string, config: ColorSchemeEmissionConfig @@ -341,7 +296,6 @@ export function assertColorSchemeEmission( } for (const [scheme, expected] of Object.entries(config.system ?? {})) { - // SAFETY: `system` is keyed by `OsScheme`; entries widen it to string. const folded = foldedFallbackFor(css, scheme as OsScheme); const guarded = [ ...schemeBlocks(css) @@ -367,10 +321,6 @@ export interface SystemFallbackParityConfig { mapping: Readonly>>; } -/** - * A guarded fallback block's declarations equal its mapped mode's attribute - * block, and follow `:root` — ahead of it they lose at equal specificity. - */ export function assertSystemFallbackParity( css: string, config: SystemFallbackParityConfig @@ -387,18 +337,13 @@ export function assertSystemFallbackParity( const blocks = schemeBlocks(css); for (const [scheme, mode] of Object.entries(config.mapping)) { if (!mode) continue; - // The theme's fallback block, not a component's own scheme condition. const block = blocks.find( (candidate) => candidate.scheme === scheme && guardedRules(candidate).length > 0 ) ?? blocks.find((candidate) => candidate.scheme === scheme); - // SAFETY: `mapping` is keyed by `OsScheme`; entries widen it to string. const folded = foldedFallbackFor(css, scheme as OsScheme); if (folded) { - // The fold is the mode's own attribute rule, so parity holds by - // construction; what remains is that it names this mode and follows - // `:root`. if (folded.mode !== mode || folded.rule.index < rootRule.index) { throw new AssertionError( `assertSystemFallbackParity: the folded '${scheme}' fallback names '${folded.mode}' (offset ${folded.rule.index}), expected '${mode}' after :root (offset ${rootRule.index})`, diff --git a/packages/_assertions/src/assert-css.ts b/packages/_assertions/src/assert-css.ts index a0db64a2c..1ee93c127 100644 --- a/packages/_assertions/src/assert-css.ts +++ b/packages/_assertions/src/assert-css.ts @@ -10,9 +10,6 @@ export class AssertionError extends Error { } } -/** - * Collapse all whitespace so minified and pretty-printed forms compare equal. - */ export function compact(value: string): string { return value.replace(/\s+/g, ''); } @@ -28,7 +25,7 @@ export function layerBlock(name: string): RegExp { return new RegExp(`@layer\\s+${escaped}\\s*\\{`); } -export const LAYER_DECLARATION_RE = /@layer\s+[\w-]+(\s*,\s*[\w-]+)*\s*;/; +const LAYER_DECLARATION_RE = /@layer\s+[\w-]+(\s*,\s*[\w-]+)*\s*;/; const DEFAULT_LAYER_ORDER: readonly LayerMarker[] = [ LAYER_DECLARATION_RE, @@ -77,8 +74,6 @@ export function assertLayerOrder(css: string, config?: LayerOrderConfig): void { } } -// `__TRANSFORM__` is an unresolved transform slot, `animus-asset:` an asset -// reference the host plugin failed to substitute. Neither may reach delivery. const PLACEHOLDER_MARKERS = ['__TRANSFORM__', 'animus-asset:'] as const; export function assertNoPlaceholders(css: string): void { @@ -112,36 +107,6 @@ export function assertClassNameFormat( } } -export interface UnresolvedTokensConfig { - forbiddenPatterns?: readonly RegExp[]; -} - -const DEFAULT_TOKEN_PATTERNS: readonly RegExp[] = [ - /\{colors\.[a-zA-Z][\w.-]*\}/, - /\{space\.[a-zA-Z][\w.-]*\}/, - /\{fontSizes?\.[a-zA-Z][\w.-]*\}/, -]; - -export function assertNoUnresolvedTokens( - css: string, - config?: UnresolvedTokensConfig -): void { - const patterns = config?.forbiddenPatterns ?? DEFAULT_TOKEN_PATTERNS; - const matches: Array<{ pattern: string; match: string }> = []; - for (const pattern of patterns) { - const m = css.match(pattern); - if (m) { - matches.push({ pattern: pattern.source, match: m[0] }); - } - } - if (matches.length > 0) { - throw new AssertionError( - `assertNoUnresolvedTokens: found unresolved token references: ${matches.map((m) => m.match).join(', ')}`, - { matches } - ); - } -} - function allLayerBlockSpans(css: string): [number, number][] { const openRe = /@layer\s+[\w-]+\s*\{/g; const spans: [number, number][] = []; @@ -163,17 +128,9 @@ function allLayerBlockSpans(css: string): [number, number][] { export interface ConditionsInsideLayersConfig { atRules?: readonly string[]; - /** - * `[start, end]` spans exempt from the layer requirement; a span suppresses - * the check over its whole character range. See `systemSchemeVariableSpans`. - */ exemptSpans?: readonly (readonly [number, number])[]; } -/** - * Every condition at-rule occurrence must fall inside a `@layer ` span. - * Vacuously green on a sheet with no condition at-rules. - */ export function assertConditionsInsideLayers( css: string, config?: ConditionsInsideLayersConfig @@ -223,10 +180,6 @@ export function assertNoEmotionImports(jsContent: string): void { } } -/** - * A production bundle carries no dev-only diagnostic string: the - * `__ANIMUS_DEV__` define folds false so the minifier drops the gated code. - */ export function assertNoDevDiagnostics( jsContent: string, marker = 'animus:drop' @@ -279,10 +232,6 @@ function layerSpans(css: string, name: string): [number, number][] { return spans; } -/** - * Body of the FIRST `@layer ` block, brace-matched, or `undefined` when - * the sheet declares no such block. - */ export function layerBlockBody(css: string, name: string): string | undefined { const [span] = layerSpans(css, name); return span ? css.slice(span[0], span[1]) : undefined; @@ -373,10 +322,6 @@ export interface KeyframesUniqueBodiesConfig { namePrefix?: string; } -/** - * One `@keyframes` block per unique frame body: the name derives from the body, - * so two names for one body means the emission path ran twice. - */ export function assertKeyframesUniqueBodies( css: string, config?: KeyframesUniqueBodiesConfig @@ -426,10 +371,6 @@ export interface SelectorEmissionConfig { minMatches?: number; } -/** - * At least `minMatches` innermost rule preludes match `pattern`, pinning the - * class to a selector position. Patterns must tolerate minified preludes. - */ export function assertSelectorEmitted( css: string, config: SelectorEmissionConfig @@ -448,10 +389,6 @@ export function assertSelectorEmitted( } } -/** - * No literal `&` survives into an emitted sheet: every authored ampersand must - * have been substituted with the composed class. - */ export function assertNoLiteralAmpersand(css: string): void { const idx = css.indexOf('&'); if (idx !== -1) { @@ -492,8 +429,6 @@ function componentClassBase( } function tokenDeclarations(css: string, token: string): string[] { - // The lookahead keeps a base token from matching its own variant tokens - // (`token--size-sm`), and a suffix from matching a longer suffix it prefixes. const tokenRe = new RegExp(`${escapeForRegExp(token)}(?![\\w-])`); const declarations: string[] = []; for (const m of css.matchAll(/([^{}]+)\{([^{}]*)\}/g)) { @@ -503,15 +438,9 @@ function tokenDeclarations(css: string, token: string): string[] { if (trimmed) declarations.push(trimmed); } } - // Declaration order is part of the comparison: it changes CSS semantics for - // duplicate and shorthand/longhand pairs, so sorting would hide divergence. return declarations; } -/** - * Declaration equality between a binding-backed component and its - * inline-authored sibling, paired by variant-option suffix; hashes differ. - */ export function assertVariantDeclarationParity( css: string, config: VariantDeclarationParityConfig @@ -549,7 +478,6 @@ export function assertVariantDeclarationParity( } } -/** The URL a `@font-face` for `family` loads, its first `url()`. */ export function fontFaceUrl(css: string, family: string): string | undefined { const face = [...css.matchAll(/@font-face\s*\{[^}]*\}/g)].find(([block]) => block.includes(family) diff --git a/packages/_assertions/src/assert-html.ts b/packages/_assertions/src/assert-html.ts index d0a4ccda9..47ff840a6 100644 --- a/packages/_assertions/src/assert-html.ts +++ b/packages/_assertions/src/assert-html.ts @@ -1,7 +1,3 @@ -/** - * Structural assertions over emitted HTML: the no-flash promise is an ORDER - * promise, so everything here compares character offsets, not mere presence. - */ import { createHash } from 'node:crypto'; import { AssertionError } from './assert-css'; @@ -10,10 +6,6 @@ import type { JsonObject } from './json'; const DEFAULT_MARKER = 'data-animus-bootstrap'; -/** - * Anything that makes the browser apply CSS. The preload counts: Next emits - * `as="style"` ahead of the link it warms. - */ const FETCHED_STYLESHEET_REFERENCES: readonly RegExp[] = [ /]*\brel\s*=\s*["']?stylesheet\b/i, /]*\bas\s*=\s*["']?style\b/i, @@ -44,8 +36,6 @@ type StylesheetReference = { index: number; }; -/** The first stylesheet reference in a ``, or why the ordering - * contract cannot be witnessed: a head with none is an empty set. */ function firstStylesheetReference( head: HeadSlice, assertion: string, @@ -79,18 +69,10 @@ function scriptRe(marker: string): RegExp { export interface BootstrapScriptConfig { marker?: string; code?: string; - /** - * Artifact `cspHash`, recomputed from the EMITTED text a browser hashes: a - * re-encoding delivery path fails here instead of as a blocked script. - */ cspHash?: string; } -/** - * The bootstrap script is in `` and precedes every stylesheet reference. - * A document with no stylesheet reference throws instead of passing vacuously. - */ -export function assertBootstrapScriptFirst( +function assertBootstrapScriptFirst( html: string, config?: BootstrapScriptConfig ): void { @@ -137,17 +119,9 @@ export function assertBootstrapScriptFirst( } } -/** - * HTML's hard limit: an encoding declaration must be serialized completely - * within the first 1024 bytes or browsers ignore it and sniff. - */ const CHARSET_BYTE_BUDGET = 1024; -/** - * The encoding declaration lives in `` and ends within the byte budget. - * Head-prepend injection pushes it toward that cliff, and overflow is silent. - */ -export function assertCharsetWithinByteBudget(html: string): void { +function assertCharsetWithinByteBudget(html: string): void { const head = headOf(html); const match = head.html.match( /]*\b(?:charset\s*=|http-equiv\s*=\s*["']?content-type)[^>]*>/i @@ -158,8 +132,6 @@ export function assertCharsetWithinByteBudget(html: string): void { { budget: CHARSET_BYTE_BUDGET } ); } - // Measured from the DOCUMENT start, what the browser counts, even though the - // search is scoped to ``, the only place a declaration is honored. const end = head.offset + match.index + match[0].length; const endByte = new TextEncoder().encode(html.slice(0, end)).length; if (endByte > CHARSET_BYTE_BUDGET) { @@ -175,10 +147,6 @@ export function assertCharsetWithinByteBudget(html: string): void { } } -/** - * Ordering and charset budget armed together: a lane that injects into - * `` and asserts ordering alone ships the overflow silently. - */ export function assertHeadInjectionContract( html: string, config?: BootstrapScriptConfig @@ -187,10 +155,6 @@ export function assertHeadInjectionContract( assertCharsetWithinByteBudget(html); } -/** - * The negative witness: a route the application never touched carries no - * bootstrap script, even in a build where another route places one. - */ export function assertNoBootstrapScript( html: string, config?: { marker?: string } @@ -205,21 +169,11 @@ export function assertNoBootstrapScript( } } -/** The metas a font preload follows. */ const FONT_PRELOAD_PRECEDING_METAS: readonly RegExp[] = [ /]*\bcharset\s*=/i, /]*\bname\s*=\s*["']?viewport\b/i, ]; -/** - * The font preload contract: `` holds exactly one font preload, with - * `crossorigin`, whose href is `href` — the URL the stylesheet's `url()` - * loads, so the browser fetches the file once — and it precedes every - * stylesheet the document fetches. Its type, when it has one, is a font MIME type: a - * browser ignores a preload whose type it does not support. It follows the - * charset and viewport metas, and the charset ends within the 1024 bytes a - * browser sniffs for it. - */ export function assertFontPreload(html: string, href: string): void { const head = headOf(html); const preloads = [...head.html.matchAll(/]*>/gi)].filter( @@ -258,7 +212,6 @@ export function assertFontPreload(html: string, href: string): void { ); } } - // An inline `