mirror of
https://github.com/pbakaus/impeccable.git
synced 2026-09-18 00:56:30 +03:00
The Rust engine: one binary replaces every script and the JS detector, fully open (#714)
* Add oracle harness: verb goldens and function-level vectors
Records stdout/stderr/exit/files for every impeccable verb over a fixed
corpus and replays them against an alternate implementation. Adds a loader
hook that captures per-function call vectors from the pure engine modules.
Prepared with AI assistance (Claude Code).
* Oracle: hook, hook-before-edit, hook-admin cases and goldens
Prepared with AI assistance (Claude Code).
* Add docs/CLI-CONTRACT.md: observable behavior of every impeccable verb
Prepared with AI assistance (Claude Code).
* Oracle: context/doctor/pin/surface-brief/critique/palette/embed/signals/csp/seed/genimg/question cases and goldens
Prepared with AI assistance (Claude Code).
* Oracle: live-mode cases and goldens (roots, inject, wrap, insert, accept, session, manual edits, daemon)
Prepared with AI assistance (Claude Code).
* Oracle: mask the binary path before HOME; export launcher env to the binary
Prepared with AI assistance (Claude Code).
* detect: set process.exitCode instead of exiting after the final write
process.exit() right after a large piped stdout write truncated JSON output
at the pipe buffer boundary; found by the oracle harness. Re-record the six
directory-scan goldens that had captured the truncation.
Prepared with AI assistance (Claude Code).
* Oracle: normalize the hook-admin command in both runtimes' forms and audit chars
Prepared with AI assistance (Claude Code).
* Skill text: invoke the impeccable launcher instead of node scripts
Every `node {{scripts_path}}/<name>.mjs` becomes `{{scripts_path}}/impeccable <verb>`
(context-signals -> signals, hook-admin -> hooks). Setup step 1 drops Node, points
Windows shells without sh at impeccable.cmd, and says the launcher runs a
self-contained binary. allowed-tools follows.
Prepared with AI assistance (Claude Code).
* Scripts dir: replace the Node scripts with the impeccable launcher
skill/scripts keeps command-metadata.json and the page JS; every .mjs entry
point, lib/, and live/ are gone (the binary owns those verbs). Adds the POSIX
launcher, impeccable.cmd, VERSION (copied from the new root ENGINE_VERSION),
scripts/fetch-engine.mjs (bun run fetch:engine) to pull the pinned binary
into skill/scripts/bin/<os>-<arch>/, and gitignores that bin dir.
Prepared with AI assistance (Claude Code).
* Build: ship the launcher instead of bundling the JS engine
readSourceFiles no longer copies cli/engine into the skill; the scripts
payload is the launcher (executable bit preserved through dist, plugin/, and
universal.zip), impeccable.cmd, VERSION (synced from ENGINE_VERSION on every
build), the page JS, and command-metadata.json. Hook manifests call
`<scripts>/impeccable hook` behind an existence guard (Codex adds a
commandWindows sibling calling impeccable.cmd; Cursor runs hook-before-edit;
GitHub keeps the git rev-parse form; Grok mirrors Claude); the Node probe and
systemMessage notice are gone. build:release fetches the pinned engine for
every target (lenient) and stages bin/<os-arch>/ into the dist skill copies
after root harness dirs and plugin/ were synced, so git-delivered trees stay
launcher-only. The detection-rule count check reads the vendored
extension/detector/antipatterns.json and is skipped when absent.
build:browser is a stub; the codex prefix rewrite leaves
`{{scripts_path}}/impeccable` alone.
Prepared with AI assistance (Claude Code).
* CLI: turn the impeccable npm package into a platform-binary shim
cli/engine, cli/lib, and cli/bin/commands are gone; their behavior lives in
the engine binary. cli/bin/cli.js now resolves the binary from IMPECCABLE_BIN,
the @impeccable/cli-<os>-<arch> optional dependency (templates under
cli/platform-packages/, published by the engine release), the
~/.impeccable/bin/<version>/ cache, or a checksum-verified download, and
execs it. package.json drops the engine dependencies and the library
exports; puppeteer moves to devDependencies for the icon scripts.
README.npm.md describes the shim.
Prepared with AI assistance (Claude Code).
* Tests: gate behavior on the oracle and the engine binary
Unit tests of the deleted Node scripts and the JS detector are removed;
their behavior is pinned by tests/oracle goldens (frozen JS behavior plus
reviewed deltas) and the engine's own tests. tests/oracle.test.mjs replays
the corpus against the binary (IMPECCABLE_BIN or skill/scripts/bin/<target>/,
via tests/lib/engine-bin.mjs) and skips cleanly without one; the framework
fixture sweep drives live-inject, live-wrap, and detect-csp through the
binary the same way. record.mjs learns --bin. The function-level vectors
under tests/oracle/vectors/calls are committed as the frozen snapshot they
can no longer be regenerated from. Suites: core trimmed to build and
transformer tests, oracle added to the default run, detector/live reduced to
packaging and reference checks, the live-e2e helper tests move to the opt-in
live-e2e lane pending its retarget, cli-remote-e2e is an empty placeholder.
Prepared with AI assistance (Claude Code).
* Docs: describe the launcher, the engine pin, and the oracle gate
CLAUDE.md gains an Engine binary section (launcher lookup order, ENGINE_VERSION,
untracked binaries, how tests get one, the oracle as behavior gate, what stays
JavaScript) and drops the Node-script and JS-detector descriptions; the CLI
and detection-rule sections point at the shim and the engine repo. README.md
states the skill needs no runtime and lists the launcher-based hook commands;
AGENTS.md follows. CLI-CONTRACT.md's intro notes the scripts it quotes are
the recorded source, not the tree.
Prepared with AI assistance (Claude Code).
* Tests: tighten the hook command guard assertion
Prepared with AI assistance (Claude Code).
* Oracle: re-golden 46 cases for the engine's own command names; record them in DELTAS.md
Prepared with AI assistance (Claude Code).
* Build: ship launcher-only release zips by default
IMPECCABLE_BUNDLE_ENGINE=1 opts in to staging the engine binaries into the
dist skill copies. Bundling every target into every provider copy put
dist/universal.zip near 340 MB, past the 25 MB Cloudflare Pages file cap
that impeccable install downloads through.
Prepared with AI assistance (Claude Code).
* Tests: drive the live-e2e orchestrator through the engine binary
The session, fake-agent loop, steer test, and manual-edit probe spawn
<binary> <verb> (live-server, live, live-inject, live-wrap, live-insert,
live-accept, live-poll, live-complete) resolved by tests/lib/engine-bin.mjs
instead of node skill/scripts/live-*.mjs; the completion typing the agent
imported from the deleted live/completion.mjs is a small local helper. The
live-e2e helper unit tests move back into the default live suite (the steer
loop skips without a binary).
Prepared with AI assistance (Claude Code).
* Tests: run new-work-e2e through the engine's serve-question and generate-image verbs
Prepared with AI assistance (Claude Code).
* Tests: point the skill-behavior harness at the launcher and engine binary
The bash tool exports IMPECCABLE_BIN so the staged skill's launcher runs
without a download; scenarios assert on 'impeccable context' instead of
context.mjs and skip without a binary.
Prepared with AI assistance (Claude Code).
* Tests: note what plugin-e2e validates before and after the generated-output sync
Prepared with AI assistance (Claude Code).
* Oracle: record the engine's 'wasm-unsafe-eval' CSP meta patch as a reviewed delta
Prepared with AI assistance (Claude Code).
* Rebase reconciliation: fold main's post-freeze work into the swapped tree
The rebase onto origin/main brought changes whose JS engine halves left the
tree with the swap. This commit reconciles what survives:
- Suite map: register main's comp-fidelity unit tests (build-phase,
comp-diff, font-match, hero-checks) in the core suite and
live-browser-ignores in the live suite.
- Payload guard: the skill scripts payload now allowlists the comp-fidelity
build pipeline (comp-spec/comp-diff/build-phase/font-match and their libs),
the one Node toolchain that has not moved into the engine.
- Drop skill/scripts/live/project-ignores.mjs, lib/live-path-globs.mjs, and
their test: they import hook-lib/live-inject/impeccable-paths, which the
swap deleted, and their consumer (the JS live server) is the engine now.
- skill text: the comp pipeline's calls to engine verbs (generate-image,
embed-prompt) use the launcher spelling.
- Oracle: re-record 17 detect goldens over the fixture set main changed
(oklch #592, color-mix #578, 1D grid #615, the two comp-fidelity rules)
and record the gap in DELTAS.md; those JS rule changes are not yet ported
to the engine, and the goldens pin its current behavior.
bun run test (oracle included) and bun run build are green on this tree.
AI-assisted change: implemented with Claude Code.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WaJv2c4oN8wS7Ttq4XRqyx
* Launcher: engine-probe PATH validation, working .cmd download path; CI: drop stale path, add oracle job
Byte-identical copies of the engine repo's launchers (engine main
af7572c): the retired 3.x npm CLI on PATH or in ~/.impeccable/bin is
rejected by the engine-probe handshake instead of hijacking every verb;
impeccable.cmd's download path is rewritten as straight-line goto flow
(the parenthesized blocks expanded %url%/%cached% at parse time, making
it dead code) with certutil sha256 verification and a windows-arm64 ->
x64 asset fallback; the final error points at the release download
instead of npm i -g (npm still serves the 3.x CLI).
ci.yml: the generated-output check no longer diffs the deleted
cli/engine/detect-antipatterns-browser.js, and a new oracle job fetches
the pinned engine (bun run fetch:engine) and replays tests/oracle/
against it. The job is continue-on-error with a loud warning until the
first engine release exists; flipping it to required is a release-time
toggle, documented in the workflow.
Verified here: sh -n on both launcher copies, bun run build green, full
oracle replay against the rebuilt engine binary green (770 pass, 0
fail), and a launcher behavior test proving a fake 3.x CLI on PATH is
skipped while the download + checksum chain completes against a local
file server.
Prepared with AI assistance (Claude Code).
* Oracle: restore detector goldens to post-fix behavior after the engine ports
The Aug 17-31 detector fixes (oklch parsing, color-mix nested hex, 1D grid
pass, comment stripping, root-relative linked stylesheets, URL userinfo
redaction, inert ignore-value refusal) and the comp-fidelity rules
organic-clip-path / buried-raster are ported to the engine. Re-records the
gap-pinning detect goldens from the fixed binary (glow.html included: its
.photo-opaque-grad column now carries the buried-raster finding it was
written for), replays the frozen checkHtmlPatterns call vectors through the
last JS engine state in history (db1462b9^; args untouched, 14 of 101
results moved), and rewrites the DELTAS gap section into the landed-ports
note. Each re-recorded json fixture golden byte-matches that JS state's
output; oracle: 770 pass, 0 fail.
Prepared with AI assistance (Claude Code).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WaJv2c4oN8wS7Ttq4XRqyx
* Oracle: pin the Aug 17-31 verb fixes ported to the Rust engine
New cases: hook-session-grok-edit-then-stop (Grok Build camelCase envelope,
end_turn/shutdown/stopHookActive Stop handling, 35ae0733 + bfe634e2 +
3c442af7, #646), hook-session-codex-stop-decision (Codex Stop emits
decision/block, c9e7cd8a, #603), and doctor-order-boot-and-deep (boot and
deep findings keep their established artifact order, 80997663).
Re-recorded goldens whose old bytes froze pre-fix behavior, with a
DELTAS.md entry naming each upstream hash: the Stop finding-cache sync
(3c442af7), the Edit|Write manifests without the retired MultiEdit matcher
(7d5c60d2), and the failWithRollback field order (1f2c3f9d).
Prepared with AI assistance (Claude Code).
* Oracle: drop a duplicated DELTAS section
The verb-fix section landed twice when two porting sessions staged the
same file; keep one copy.
Prepared with AI assistance (Claude Code).
* Oracle: pin the hooks ignore-value inert-entry refusal
Three hadmin-ignore-value-inert-* cases record the engine's port of
be87f5eb (#662) to hooks ignore-value: an exact value for a rule whose
findings can never extract one is refused with the wildcard-plus-file
route (and no config write), while the wildcard scoped form for the same
rule is accepted. Goldens recorded from the engine binary and verified
byte-for-byte against the ea360025 hook-admin.mjs on the same sequences.
No existing golden changes, so no DELTAS entry is owed.
Prepared with AI assistance (Claude Code).
* Launcher: fail closed on a missing download checksum (engine triage C1)
Byte-identical sync of the engine repo's launchers: a freshly downloaded
engine binary now runs only after verifying against its .sha256 sidecar.
A sidecar that cannot be fetched, or a machine with no sha256 tool,
refuses the download instead of exec'ing an unverified binary; the
wget-only path fetches the sidecar too. Binaries already on PATH or in
the cache that pass engine-probe are unaffected.
Prepared with AI assistance (Claude Code).
Co-Authored-By: Claude Code <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WaJv2c4oN8wS7Ttq4XRqyx
* Enforce engine-before-skill release order (triage D4)
The launcher, npm shim, and `impeccable install` all resolve the engine
binary for the pinned ENGINE_VERSION, so a skill/CLI release or a rust-swap
merge published ahead of the engine release + platform packages dead-ends
every install path. Add a mechanical guard:
- scripts/check-engine-release.mjs: verifies all five dist binaries +
.sha256 and the five @impeccable/cli-<os>-<arch> npm platform packages
exist for the pinned ENGINE_VERSION; names missing assets, exits non-zero.
Honors IMPECCABLE_DOWNLOAD_BASE.
- release.mjs: hard-fails release:skill and release:cli when assets are
missing; extension is exempt (vendored WASM detector, no engine exec).
- CI engine-release-ready job: runs the check, continue-on-error with a
loud ::warning until the first engine release exists (flip to false then).
- CLAUDE.md Releases: documents the enforced ordering.
Prepared with AI assistance (Claude Code).
* Oracle: re-record the Sep-1 verb fixes ported to the Rust engine
Five fixes landed on main in JS between the swap branch and its rebase and were
ported to the engine; the goldens they touch are re-recorded from the fixed
binary, each engine output first diffed byte-for-byte against the upstream JS on
the same inputs. DELTAS.md documents every case with its upstream hash.
- critique-* (usage/unknown/latest-existing/write-then-read/write-monorepo-child):
the #660 critique close path (identity + fingerprint freshness, ~NNNN
collision suffix, closed flag, close verb, latest --json). Upstream 5211bdf4.
- detect-* (new overused-font fixture cases, dir/scope/no-advisory sweeps):
the #678 overused-font primary-face change (a system stack keeps its system
face, so a Roboto fallback no longer flags). Upstream 2cfd6076.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WaJv2c4oN8wS7Ttq4XRqyx
* Tests: fix pre-existing release-guard staging on the swap branch
release.test.mjs was already red on the swap branch: release.mjs imports
check-engine-release.mjs and fetch-engine.mjs (the D4 engine release-order
guard), which the temp work tree never staged, so every dry run failed to
resolve the module instead of exercising the guard. Stage both modules and set
IMPECCABLE_SKIP_ENGINE_CHECK=1 so the guard does not probe the network; this
suite predates the guard and only covers the version/changelog/artifact checks.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WaJv2c4oN8wS7Ttq4XRqyx
* oracle: pin E8 stale-hook-manifest detector fallback (context)
Cover the v3-to-launcher upgrade fix (triage E8) recorded from the engine
binary and hand-reviewed:
- context-stale-hook-manifest: a .claude/settings.local.json naming the retired
`node .../hook.mjs` script under the claude-code provider emits
MANUAL_DETECTOR_REQUIRED, because the stale marker no longer counts as an
active hook (its script is gone after the update).
- context-launcher-hook-active: the same manifest in the launcher form still
suppresses MANUAL_DETECTOR_REQUIRED, confirming the launcher marker is
recognized as active.
The only difference between the two goldens is the MANUAL_DETECTOR_REQUIRED
block. No existing golden moved: every other context case runs under the source
provider, whose hook-manifest list is empty, so none of them scan a manifest.
Also null IMPECCABLE_PROVIDER_ID in the case BASE_ENV so a recording machine's
value cannot leak. DELTAS.md records the intentional divergence from JS parity.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WaJv2c4oN8wS7Ttq4XRqyx
* Tests: stop two harness hangs from wedging a whole run
Two suites could hang forever and never print a tally, because the one
mechanism that could interrupt the wedged work was missing on both paths.
Hang 1 (bun run test / build-phase.test.mjs): the test's run() helper
spawned every child with spawnSync and no timeout. spawnSync blocks the
test worker's thread, so node's --test-timeout (an event-loop timer)
cannot interrupt a child that wedges (a fork/exec blocked on OS resources
under concurrency, a gate's comp-diff grandchild, or a stray browser
launch). Bound every child with spawnSync timeout + killSignal SIGKILL so
a wedge becomes a fast, named failure the next test survives.
Hang 2 (bun run test:skill-behavior): runTurn called generateText with no
client-side deadline, so a stalled provider stream kept the fetch (and the
whole node process) alive past the per-test timeout, producing no tally.
Attach a real AbortSignal (default 840s, under the 900s per-test cap):
on expiry the fetch aborts, the turn throws, and the scenario
fails-and-continues. The unref'd timer is cleared on completion.
Runner backstops: run-tests.mjs now spawns each command as a detached
process-group leader and enforces a per-suite wall-clock cap that SIGKILLs
the entire group (workers, grandchildren, browsers) on expiry, with
SIGINT/SIGTERM forwarded so Ctrl-C still reaps the tree. The core node
batch gets a finite --test-timeout (180s); skill-behavior gets a 60min
group cap. Env overrides: IMPECCABLE_TEST_WALL_CLOCK_MS,
IMPECCABLE_SKILL_BEHAVIOR_TURN_TIMEOUT_MS,
IMPECCABLE_BUILD_PHASE_RUN_TIMEOUT_MS.
Proof: bun run test green twice (~60s); scoped claude-sonnet-5
skill-behavior sweep terminates with a tally (20 tests, ~32min) where the
840s abort caught a wedged redesign turn and the sweep continued instead
of hanging.
Prepared with AI assistance (Claude Code).
* launcher: export skill-dir env before the IMPECCABLE_BIN exec (sync engine fix)
Prepared with AI assistance (Claude Code).
* Node-free swap: comp-fidelity verbs move to the engine
The four comp-fidelity scripts (comp-spec, comp-diff, font-match, build-phase)
and their six libs are ported into the impeccable-engine binary. This removes
the last Node .mjs from the skill: `git ls-files skill/scripts | grep '\.mjs$'`
now returns nothing.
- reference/new-work.md, reference/visualize.md, and the asset-producer /
finish-reviewer agents now invoke `{{scripts_path}}/impeccable <verb>` instead
of `node <script>.mjs`.
- Deleted the ten ported .mjs and the four JS unit tests that imported them
(their behavior is now covered by the engine's Rust tests and the oracle);
removed those files from scripts/test-suites.mjs.
- Added oracle cases (comp-*, font-match-*, build-phase-*) over a comp-basic
workspace, recorded from the engine binary; the deterministic outputs are
byte-identical to the JS the scripts left behind.
- docs/CLI-CONTRACT.md documents the four verbs, the CDP font rendering, and
the runtime-resolved (never-committed) font-index catalog.
The font-index catalog JSON stays shipped in the skill (data/font-index.json);
the engine resolves it at run time and never vendors it.
Prepared with AI assistance (Claude Code).
* reorg: public plumbing for the in-repo Rust workspace and the two-release flow
The engine binaries move from the impeccable-dist channel to this repo's own
GitHub Releases (tag engine-v<ENGINE_VERSION>), and the closed detector the
engine links arrives as detector-v<DETECTOR_VERSION> releases on the same
repo. This commit wires the public side for that; the crates themselves land
in the next commit.
- Launcher (sh + cmd), npm shim, fetch-engine and check-engine-release now
download from github.com/pbakaus/impeccable/releases/download/engine-v<X>/.
- release.mjs gains `engine`: verifies ENGINE_VERSION against the platform
package pins and the detector release, tags, pushes; release-engine.yml
builds the five targets and publishes. check-detector-release.mjs is the
matching release-order guard (with tests).
- Root Cargo.toml (workspace, lto = false with the reason), rust-toolchain.toml
(exact pin), DETECTOR_VERSION, /target ignored.
- CI: rust + rust-windows jobs and an oracle job that replays the goldens
against a source build, warn-only until the first detector release exists;
ci-test-plan exposes a `rust` output.
- docs/ENGINE.md (the crate map and the closed-detector mechanism) and the
CLAUDE.md engine, release-order and rules sections.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* reorg C: the open Rust runtime joins this repo as one Cargo workspace
The engine no longer lives in a separate repo. `crates/` is a snapshot of the
open crates (foundation, core, common, context, live, hook, skills, comp,
comp-verbs, html, browser, detect, cli) plus `Cargo.lock`, taken as a git
archive of the engine repo at the commit that finished the boundary split.
None of that repo's history comes with it, and none of it should: the closed
half stays private.
The closed half is the rule engine. It ships as a prebuilt native archive per
target, `libimpeccable_detector.a`, published as a `detector-v<X>` GitHub
Release on this repo. `crates/core/build.rs` resolves and links it three ways:
`IMPECCABLE_DETECTOR_LIB=<dir>` for a local detector build, else the
`~/.impeccable/detector/<version>/<target>/` cache, else a download verified
against its `.sha256` sidecar. `crates/core` is a thin shim over a three-symbol
C ABI; nothing above it knows the boundary exists.
What changed versus the engine repo copy:
- Every crate manifest moves from `license-file.workspace` to
`license.workspace` (this workspace declares Apache-2.0), and the workspace
gains the `postcard` dependency the boundary encoding needs.
- The launcher contract test reads `skill/scripts/impeccable{,.cmd}` instead of
a sibling `launcher/` dir, and `engine_binary` downloads from
`github.com/pbakaus/impeccable/releases/download/engine-v<version>/` instead
of the retired dist repo. No oracle golden carried the old URL, so no
re-recording was owed.
- The tests that hunted for a public repo through `IMPECCABLE_PUBLIC_REPO`,
`../impeccable-second` or a hardcoded home directory now resolve the root as
`CARGO_MANIFEST_DIR/../..`, because they are in it. The env var stays as an
override for an out-of-tree checkout.
- The in-page bundle (`detect-antipatterns-browser.js`, 2 MB of generated wasm
glue) is no longer tracked. `crates/core/build.rs` resolves it beside the
archive, hands the path to `impeccable_core::browser::IN_PAGE_BUNDLE_JS`, and
live mode serves that. `scripts/check-detector-release.mjs` now requires it
and its `.sha256` in a detector release.
- The live crate embeds `skill/scripts/live-browser*.js` and
`modern-screenshot.umd.js` directly rather than through vendored copies, so
the binary and the installed skill cannot drift.
- `crates/browser/assets/` (an unused second copy of the bundle) is gone.
- `tests/lib/engine-bin.mjs` also accepts `target/release/impeccable`, so a
plain `cargo build --release -p impeccable` is enough to run `bun run test`.
Verified with the archive from a local detector build: `cargo test --workspace`
267 pass, oracle 795 pass / 0 fail / 0 missing, `bun run build` clean, the
default suite green, and the launcher's `engine-probe` handshake answering
through `skill/scripts/impeccable`.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* docs: bring RUNTIME-ENV and PORTING-GUIDE over with the runtime
They describe the binary's environment contract and the parity method every
crate here was ported with; both belong next to the crates now.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* core/build.rs: refuse a detector archive built by another rustc, in plain words
The archive links only against the exact rustc that built it; a mismatch
used to surface as pages of undefined std symbols from the linker. The
detector repo now writes rustc-version.txt next to the archive (and ships it
with the release); when it is present, build.rs compares it with its own
compiler and names both versions.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* build:extension: ship the wasm-core extension shell and vendor its detector from the detector release
`bun run build:extension` was broken on this branch: it still imported the
deleted JS engine (cli/engine/registry/antipatterns.mjs,
scripts/lib/browser-detector-bundle.js).
The shipped shell now matches the new design. The content script only
snapshots the DOM; an extension-owned offscreen document runs the
WebAssembly rule core over that snapshot, so the scanned page's CSP no
longer matters. That replaces the old approach of injecting a JS rules
bundle into the page. New files: extension/offscreen/offscreen.html, plus
the "offscreen" permission and a 'wasm-unsafe-eval' extension_pages CSP in
the manifest.
The manifest version stays at 1.3.3. The shell's own manifest carried
2.0.0; feature branches never bump versions, so the bump is a release step.
The five generated detector pieces (core.js, core_bg.wasm, snapshot.js,
overlay.js, antipatterns.json) are vendored at build time into the
gitignored extension/detector/ by the new scripts/lib/detector-bundle.mjs,
which resolves them the same three ways crates/core/build.rs resolves the
native archive: IMPECCABLE_DETECTOR_LIB/extension-detector/, the
~/.impeccable/detector/<DETECTOR_VERSION>/ cache, then a checksum-verified
download of detector-browser-bundle.zip from the detector release.
antipatterns.json is no longer regenerated here.
The zip packaging is unchanged. The Firefox variant still builds so
`web-ext lint` keeps covering the shared shell, but it cannot scan: Gecko
has no chrome.offscreen API. The build prints a one-line warning saying so.
Also here: a referenced-path check that fails the build when the manifest
or the service worker points at a file that is not in extension/, a
resolver unit test wired into the core suite, and the detector rule count
in the READMEs synced to the 61 the vendored registry carries.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* oracle: replay byte-for-byte on Linux too
The corpus was recorded on macOS and eight cases failed on ubuntu CI for
reasons that were all environment, not behavior:
- stageWorkspace returns the realpath of the staged dir. macOS's tmpdir is a
symlink and two goldens (context-dir-override, live-accept-source-locked)
had recorded that artifact; both re-recorded, reviewed in DELTAS.md. The
source-locked case now actually exercises the lock it is named for.
- context-lowercase-product-name declares platforms: ['darwin', 'win32'];
run.mjs skips such cases elsewhere and says so in the summary.
- The hook-project workspace's empty provider skill folders (.claude,
.cursor) are now tracked with .gitkeep; git cannot track empty
directories, so a fresh checkout had none and hooks on found nothing to
repair.
- crates/live's read_dir_raw sorts entries by name: the goldens hold the
order macOS returned, Linux returns hash order, and the source-candidate
lists in live-commit output depended on it.
macOS: 795 pass, 0 fail. The Svelte accept cases additionally need the
public repo's node_modules on the machine that runs them (CI now installs
them).
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* oracle: mask <HOME> only at path boundaries (a short home like /root ate 'roots.json')
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* oracle: track live-html's dist/generated.html (the root dist/ ignore hid it from CI checkouts)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* release-engine: darwin-x64 builds on macos-14 (macos-13 is retired)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* Open the detector: the rule crates join the workspace, the C-ABI goes away
The detector is open source. The rules it ships were already public in this
repo's git history and in every npm tarball of the JS engine, so a closed
binary bought nothing it could keep; the moat is the service (the catalog,
the labs, the review pipeline), not the check functions. Keeping them behind
a prebuilt archive cost a C-ABI, an exact toolchain pin, a build-time
download, a second release to order ahead of every engine release, and a
serde layer that had to serve two encodings.
Deleted
- crates/core/src/ffi.rs, crates/core/build.rs, crates/core/tests/boundary.rs
and the shim modules under src/checks and src/browser.
- crates/foundation/src/boundary.rs and the postcard dependency.
- DETECTOR_VERSION, scripts/check-detector-release.mjs and its test, the
check:detector-release script, the detector gate and
IMPECCABLE_SKIP_DETECTOR_CHECK in scripts/release.mjs.
- scripts/lib/detector-bundle.mjs and tests/detector-bundle.test.mjs (the
vendoring path for the closed browser bundle).
- scripts/build-browser-detector.js and the build:browser script (a stub
since the JS engine left the tree).
- xtask's detector-archive subcommand and its public-repo lookup.
Came back
- crates/core is now the rule logic itself: every check_* / scan_*, the
browser adapters, the visual-contrast decisions. It re-exports foundation
as before, so no consumer changed. Its vectors dispatcher is the union of
both id tables again, and tests/vectors.rs replays the frozen vectors
straight through it.
- crates/wasm and crates/xtask join the workspace. cargo xtask bundle builds
the in-page bundle from browser-bundle/ plus the wasm core, writes
dist/, refreshes the tracked crates/live/assets/detect-antipatterns-
browser.js, and writes extension/detector/. bun run build:extension runs
it instead of downloading.
- crates/live/assets/detect-antipatterns-browser.js is tracked again; live
mode embeds it and serves it as /detect.js.
- Serde is back to plain derives: no is_human_readable branch in
js::json_number, derived Serialize for Rgba and BrowserFinding with their
skip_serializing_if attributes.
- profile.release has lto = "fat" again; rust-toolchain.toml is plain
stable plus the wasm32 target. The rust, rust-windows and oracle CI jobs
lose continue-on-error and can be required.
Verified
- cargo build --workspace --all-targets: clean, no warnings.
- cargo test --workspace: 346 pass, 0 fail (the 8 boundary tests are gone
with the boundary).
- cargo build -p impeccable-wasm --target wasm32-unknown-unknown --release: ok.
- cargo xtask bundle && cargo xtask bundle --check: reproducible; the
regenerated bundle is committed (it differs from the archived one, which
was built with a pinned rustc and lto = false).
- cargo build --release -p impeccable: no linker warnings, 12.5 MB (the
same source at lto = false is 13.1 MB).
- oracle: 795 pass, 0 fail, 0 accepted deltas, 0 missing goldens.
- bun run build, bun run build:extension, web-ext lint (0 errors,
8 warnings), bun run test: 363 + 80 + 1 + 1 + 133 + 180 + 4 pass, 0 fail.
- impeccable detect --no-config --json tests/fixtures/antipatterns: 128.7 ms
median of 5.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* core: doc comments drop the open/closed split
The rule crate and the foundation crate are both Apache-2.0 in one
workspace now, so "open", "closed" and "crosses the boundary" no longer
describe anything. Comments only.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* Rule packs: downstream crates add rules on all three engines; wasm detect surface
A crate that depends on this workspace can now add rules without forking
it. `impeccable_core::rule_pack::RulePack` (object-safe, Send + Sync +
Debug) carries a pack's registry rows plus three hooks that default to
empty: `check_text` for the text engine, `check_element_dom` and
`check_page_dom` for the browser driver. `impeccable_html::StaticRulePack`
adds `check_document` for the static engine, where the document model
belongs to the html crate and detect cannot name it.
The registry keeps ANTIPATTERNS as the built-in list; `registry::extend`
appends a pack's rows and every lookup consults them after the built-ins,
so a pack can never shadow a built-in id (extend panics on a collision and
is idempotent per slice). `all_antipatterns()` is the built-ins followed by
the registered rows.
Hook order, chosen so built-in output cannot move:
- detect_text: after every matcher, analyzer and the dedupe, before inline
ignores, so `impeccable-disable` waives pack rules like built-in ones.
- detect_html_source: after the element rules, the design-system merge and
the page passes, again before inline ignores. One pack pass per HTML
file: the document hook when set, otherwise the text hook over the raw
source, so a pack implementing both never reports twice.
- collect_browser_findings: the element hook at the end of the per-element
loop through the same disabled-rules filter and group, the page hook
after every built-in page pass with the same el-or-body attribution.
A pack travels on TextOptions / ScanOptions, DetectHtmlOptions
(static_rule_pack plus rule_pack), StaticHtmlEngine, and BrowserConfig
(serde-skipped: a pack is a Rust value, not JSON from the page). The
shipped binary installs none.
`crates/wasm --features detect` exposes the two file engines as JSON
exports for hosts that cannot exec the binary: `detect_text_json` and
`detect_html_source_json`, options `{ inlineIgnores?, designSystem? }`,
returning the findings array `detect --json` prints. `antipatterns_json`
now includes a pack's rows. `set_rule_pack` and `set_static_rule_pack` are
Rust-only, for a crate that links this one as an rlib.
Tests: registry extension and collision in foundation, one test pack per
engine (crates/core, crates/detect, crates/html tests) proving each hook
fires, that the built-in findings are unchanged, and that the waivers and
the disabled-rules list cover pack rules, plus the wasm export shapes.
Workspace tests 346 to 361, oracle 795/0 unchanged.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* docs: the cutover checklist under the open design
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* bundle: the page JS and the bundler become a library crate downstream packs can reuse
The in-page bundle, the extension pieces, the registry JSON and the
wasm-pack call were reachable only through `cargo xtask bundle`, which read
`browser-bundle/*.js` from the repo root. A downstream crate that links
impeccable-core + impeccable-wasm with its own rule pack had to copy the
page JS to produce a detector bundle for its module.
They move to `impeccable-bundle` (crates/bundle), which embeds every
`browser-bundle/*.js` with `include_str!` and exposes `in_page_bundle`,
`extension_pieces`, `registry_json`, `check_capture_contract` and
`wasm_pack_build`. Nothing writes files or exits the process; the caller
places the bytes. `registry_json` now reads `all_antipatterns()`, so an
installed pack's rows land in `antipatterns.json` too (no built-in change).
xtask becomes the workspace's caller and writes the same files to the same
places; `cargo xtask bundle` is byte-identical, tracked live asset included.
`IMPECCABLE_BUNDLE_SKIP_WASM_PACK` is the skip switch's new name, the old
`IMPECCABLE_XTASK_SKIP_WASM_PACK` still works.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* The immediate tier moves to the registry, and reaches wasm
The design hook's immediate-tier list is the set of rule ids worth fixing
at the edit site, and a downstream reviewer wants the same set to decide
how loudly a finding is reported. `impeccable-hook` is native-only, so the
list moves to `impeccable_core::registry` (the hook re-exports it) and the
`detect` feature gains `immediate_tier_rules_json()`.
The export is behind `detect`, which the in-page bundle does not build, so
the tracked browser asset is unchanged.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* docs: Pristine tracks the engine by revision pin, not npm
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* docs: the cutover checklist is maintainer-side, not part of the tree
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* Port: Fix flat type hierarchy false positives (#702)
Upstream sha 84728e9ce4.
The rule now reads rendered semantic roles and the dominant size per role
instead of the raw set of font sizes on the page, and it fires only when
every adjacent role step is under 1.25x.
- crates/core checks::rules gains TYPE_HIERARCHY_SELECTOR / MIN_ROLES /
MIN_STEP_RATIO, typeHierarchyRole, dominantTypeRoleSize and
checkFlatTypeHierarchySamples, the shared half of checks.mjs.
- crates/core browser::page_checks gets checkFlatTypeHierarchyFromDoc over
the Dom trait, with the overlay skip selector checkTypography passes.
- crates/html page.rs gets the same walk over StaticDocument.
- crates/detect drops the source-only analyzer: flat-type-hierarchy leaves
REGEX_ANALYZERS, the text-content analyzers shift to index 1, and
analyzer_rule_id loses its first row.
- crates/html cascade defaults gain contentVisibility, and crates/foundation
registry carries the reworded description.
Goldens re-recorded (the binary now matches origin/main's JS engine on every
one of these fixtures, verified by scanning the shared corpus with both):
glow, icon-tile-stack, layout, modern-color-borders, motion,
named-color-borders, numbered-section-markers, oklch-neon-text,
typography-should-flag, json and text.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* Port: Fix detector URL scans and advisory handling (#709)
Upstream sha fa44839f72.
Advisory handling. `severity` becomes the canonical registry field: the
`advisory` bool leaves `Antipattern`, `advisory_rule_ids` filters on
`severity == "advisory"`, and `derive_advisory_flag` stamps the finding's
`advisory: true` from the effective severity, so a per-finding promotion or
demotion carries the flag. The html and browser engines call it after their
severity override; the detect CLI and the hook accept either spelling; the
driver's serializer and the wasm registry exports derive it the same way.
em-dash-overuse moves from `advisory: true` to `severity: "advisory"`.
URL scans. `expand_joined_url_targets` splits an argv value that is entirely
whitespace-separated URLs and leaves paths with spaces alone. The browser
driver reads the readable linked-stylesheet corpus into the HTML pattern
corpora and resolves a finding's selector with `selector_nodes_for_live_dom`
/ `pseudo_element_host_selector`, so an unresolvable selector drops the
finding instead of keeping it page-level. The CSSOM walk itself is page JS:
`browser-bundle/15-snapshot.js` gains `__snapLinkedStylesheetText` (grouping
rules flattened, container-query probes, effective keyframes) and puts it in
the snapshot as `linkedCss`; `10-probe.js` exposes the same for the in-page
route, and the Dom trait carries `linked_stylesheet_text`.
Also `enclosing_css_selector` blanks comments before hunting the previous
declaration delimiter, and `check_typography` reports the uniquely most-used
family instead of every family over a 15% share.
Verified: `impeccable detect --no-config --json tests/fixtures/antipatterns`
is now byte-identical to `node cli/bin/cli.js` on an origin/main worktree
over the shared corpus (432 findings). The two changed lines in
tests/oracle/vectors/calls/rules.checks/checkHtmlPatterns.jsonl were
re-recorded by running origin/main's `checkHtmlPatterns` over the frozen
args; only the comment-polluted selector changed. Goldens re-recorded for
the advisory partition (config-*, fixture gemini/gpt-tells,
numbered-section-labels, scoped-ignore, shape-assembled-illustration,
color, em-dash-entities) and the help text, each cross-checked against the
JS on origin/main.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* Port: stop gray-on-color false positives on Tailwind opacity and JSX (#707)
Upstream sha 32b270f4e8.
`find_solid_chromatic_bg` replaces the bare `bg-<hue>-<n>` match in both
engines: a `bg-blue-500/10` tint is a wash, not a solid fill. The `regex`
crate has no lookahead, so the maximal digit run plus the word boundary is
matched as before and the byte after it is tested for `/`.
The text engine gains the JS-source scanner (`scan_js`) and the scope
helpers on top of it: `containing_markup_tag` keeps a gray text class from
pairing with a background in a sibling tag on the same line, and
`find_ternary_split` / `exclusive_class_scopes` split a `cond ? a : b`
class expression into its arms, recursing into nested ternaries, ignoring
`?.` and `??`, and keeping a common prefix and post-ternary suffix in every
arm. `MatchCtx` now carries the match offset the scope lookup needs.
Verified against origin/main's JS: all eleven cases from the upstream test
file plus a nested / nullish / suffix set produce byte-identical findings on
both engines; they are pinned as Rust unit tests in `regex_matchers` and
`checks::rules`. The shared fixture corpus stays byte-identical.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* Port: resolve unique --target names in monorepos (#706)
Upstream sha 8b326fc81e.
`resolve_target_path` / `find_unique_bare_target` in `crates/context`: a
`--target` that does not exist and reduces to a single path segment under
cwd resolves to the one workspace candidate with that name, so `--target a`
selects `apps/a`. A caller that already absolutized the name against cwd
(live and the other helpers do) takes the same route. Ambiguous or unknown
names still report the miss.
The context CLI resolves the target once and hands the resolved path to
`load_context`, replacing `path_exists_for_target`.
Oracle: four new `context-monorepo-target-bare-*` cases (bare name,
absolutized bare name, unknown name, bare name from a child cwd).
`context-monorepo-target-b-inherits` was re-recorded: resolving the target
before `load_context` changes its `surfaceBriefReason` from `not-found` to
`invalid-target`, which is what origin/main's `context.mjs` prints for the
same run.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* Port: Fix Next.js 16 CSP and parent hook discovery (#710)
Upstream sha 672ca29642.
CSP. `detect-csp` recognizes Next.js 16's `proxy.{ts,js,mjs}` request hook
beside `middleware.*`, but only where it sits at a project root or its `src/`
directory: the scan root itself, or a nested directory carrying a Next
project marker (a `next.config.*`, an `app` / `pages` dir, or a `next`
dependency). A same-named helper elsewhere in the tree is not the framework
hook.
Context. `find_git_boundary_root` gives `resolve_project` a git-boundary
notion: an explicit target inside its own repository resolves against that
repository, and an external target resolves against its own root, so caller
context never leaks across the boundary. `hook_manifest_search_roots`
replaces the cwd/projectRoot/repoRoot triple with a walk up from the
project root that stops at the first git boundary, and each root's own hook
lifecycle config is honored before its manifest counts as coverage.
Verified against origin/main's JS: nine `detect-csp` placements and five
hook-discovery scenarios (enclosing harness root, that root disabled,
sibling target, nested git target, markerless nested git target) produce
identical output.
Oracle: five `csp-proxy-*` cases and five `context-hook-*` /
`context-markerless-nested-git-target` cases. Four route-target goldens were
re-recorded because #710 resolves a `/`-prefixed target outside the
workspace; each was cross-checked against origin/main, and
`surface-brief-write-route` has a DELTAS entry for the one wording
difference (an unwritable filesystem root).
`tests/framework-fixtures.test.mjs`'s new proxy-placement block came in from
the merge importing the deleted `detectCsp`; it now drives `detect-csp`
through the binary like the rest of that file.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* Port: fail URL scans when the browser is unavailable (#711)
Upstream sha f2f9958be1e6a4ecb1fbd5ef1ae1b7d9c53e0d24 (Fix: fail URL scans
when the browser is unavailable).
`detect` gains an operational-failure flag. Exit 1 now means at least one
requested target could not be scanned, and it takes precedence over exit 2,
because findings from the targets that did scan do not turn a partial scan
into a complete one. The flag is set by an unreachable path, an unreadable
directory or file in a dir walk, a per-file scan that throws, a URL scan
that throws, and a shared-browser setup failure.
- `walk_dir_reporting` and `build_import_graph_reporting` take a read-error
callback; the plain wrappers stay for callers that do not report. A file
the graph could not read is skipped for the scan too.
- `SharedBrowser::ensure_launched` is the eager half of
`createBrowserDetector()`: the CLI brings the browser up before the loop so
a launch failure prints one `Error:` line and every URL target is skipped,
instead of the lazy launch reporting once per URL.
- The static engine and the text path spell a permission failure the way Node
does (`EACCES: permission denied, open '<path>'`), which is what
`Error: cannot scan <target>: <message>` prints.
- Usage text and docs/CLI-CONTRACT.md carry the exit-status block.
Verified against origin/main's JS: missing target, missing target alongside a
flagging file, unreadable file, unreadable file beside a readable sibling,
unreadable directory, unreadable nested directory, a clean scan, and a
browser-unavailable scan of one and of two URLs all agree on exit code,
stdout and stderr (the browser-not-found wording is the pre-existing
puppeteer-vs-discovery difference).
Oracle: `detect-missing-file` and `detect-missing-file-json` re-recorded at
exit 1, plus new `detect-missing-file-with-findings`,
`detect-unreadable-file-json` and `detect-unreadable-file-in-dir`, each
cross-checked against origin/main. `detect-help` carries the new block.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* Port: OpenCode slash command bridge (#483)
Upstream sha 9736a9f6e9.
OpenCode does not honor `user-invocable: true` on SKILL.md frontmatter, so a
pinned skill never reaches its slash menu. `pin` now writes
`commands/impeccable-<cmd>.md` on the OpenCode command schema instead, and
skips `.opencode` in the SKILL.md loop so no unreachable
`.opencode/skills/<cmd>` is left behind. `unpin` mirrors it, marker-guarded,
and reaches both scopes even when the skill itself is gone.
`find_opencode_commands_dirs` covers the project-local dir when the project
has the skill and the user config dir when Impeccable is installed globally,
resolving that dir the way the CLI does (`OPENCODE_CONFIG_DIR` ->
`XDG_CONFIG_HOME/opencode` -> `~/.config/opencode`).
The build-tooling half of the upstream change (transformers, the OpenCode
command the build generates, `root-commands-sync`) came in with the merge and
needed no port.
Verified against origin/main's pin.mjs across seven scenarios (no harness,
project scope, user scope, a foreign command file, pin then unpin, unpin over
a foreign file, unpin with nothing pinned): identical stdout, identical file
sets, identical file contents apart from the one deliberate difference.
Oracle: five `pin-opencode-*` cases, with a DELTAS entry for the bridge body
naming the launcher rather than `node .../context.mjs`.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* Port: Fix Codex skill version metadata (#703)
Upstream sha 482368511a.
Codex's validator rejects unknown top-level keys, so the Codex and `.agents`
skills now carry `version` under the spec-defined `metadata:` map. Both
version readers learn the same parser: `parse_skill_frontmatter_version` in
`crates/context` (the boot update check) and `extract_version` in
`crates/skills` (`getSkillsVersion`). A metadata version wins, a legacy
top-level one still reads, only the map's own indent level counts, tabs count
as two spaces, and a comment line is skipped.
The build-tooling half (`versionInMetadata` on the two providers, the YAML
emitter's nested-object branch) came in with the merge.
Fourteen frontmatter shapes were recorded from origin/main's
`parseSkillFrontmatterVersion` and pinned as unit tests in both crates.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* Port: Fix skill subcommand help handling (#708)
Upstream sha a264199177.
`install`, `link`, `update` and `check` render static help before entering
any operational path, through both the top-level verb and the legacy `skills`
namespace, for `--help` and `-h` alike.
Verified against origin/main's `cli/bin/cli.js`: all six spellings produce
identical text and exit codes.
Oracle: a new `tests/oracle/cases/skills.mjs` with seven help cases. Only the
help paths are pinned there; every other installer path writes into harness
directories or reaches the network.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* Oracle: goldens for the three fixtures the merge added
`tests/fixtures/antipatterns/` gained `flat-type-hierarchy.html` (#702) and
`linked-url-patterns.{css,html}` (#709) with the merge, so the corpus
generator produced six `detect-fixture-*` cases with no goldens and the
directory-wide cases (`detect-dir-*`, `detect-scope-*`, `detect-no-advisory-*`)
moved.
Every golden here was recorded from the binary and then cross-checked against
`node cli/bin/cli.js` on an origin/main worktree over the same files: the six
per-fixture cases agree byte for byte in JSON and text, and a full scan of
`tests/fixtures/antipatterns` produces 432 findings identical on both engines
after normalizing the repo path.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* Port: the installer half of the OpenCode command bridge (#483)
Upstream sha 9736a9f6e9, the part of it that
lives in `cli/bin/commands/skills.mjs` rather than `pin.mjs`.
`copy_provider_commands` mirrors `copy_provider_skills` for a provider's
compiled `commands/` dir: project scope writes `<root>/<configDir>/commands`,
user scope writes the config dir OpenCode actually scans
(`OPENCODE_CONFIG_DIR` -> `XDG_CONFIG_HOME/opencode` -> `~/.config/opencode`),
and a pre-#406 global install at `~/.opencode/commands/` loses exactly the
files just written while siblings, symlinked dirs and home-rooted git repos
are left alone. It runs on install, on the reinstall refresh, on update, and
on link, which is the only path that can deliver the bridge to a linked
install.
`is_up_to_date` now compares the bundle's command files too, so an install
whose skills match but whose bridge is missing or drifted refreshes instead of
reporting success while the slash command stays absent. Only bundle-shipped
files are compared, so a pinned shortcut never affects freshness.
`tests/copy-provider-commands.test.js` arrived with the merge importing the
deleted `cli/bin/commands/skills.mjs`; its scenarios are ported to
`crates/skills/tests/provider_commands_tests.rs` (project scope, the three
user-scope dir resolutions, the legacy migration and its two guards, a
provider with no commands dir, and the four `isUpToDate` command-awareness
cases), and the file is removed and deregistered.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* CI: the first full run on the branch, three fixes
- The oracle harness masks the climb to the root a /-prefixed target
produces (<UP_TO_ROOT>/): the number of `../` is the staged tmpdir's depth
(7 on macOS, 2 on Linux), not the verb's behavior. surface-brief-path-slash
re-recorded.
- Two context test helpers canonicalized their temp dir, which on Windows
yields a \\?\ verbatim path that takes `/` literally; they strip the prefix
like Node's realpathSync. The critique-storage identity test compares
against the platform's own resolved path.
- Every job that drives the binary end to end (live-e2e smoke and full,
accept-cleanup, the DeepSeek sweep, the remote CLI smoke) builds it from
the checkout first; before, they looked for a release that does not exist.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* context tests: the verbatim-prefix strip spells the prefix once
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* context test: derive the snapshot identity from the verb's own resolver
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* context test: JSON-quote the snapshot identity, as the verb does
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* detect test: import resolution against platform-form paths
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* hook test: the stock cache path in the host's path form; Windows CI runs every crate's tests before failing
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* windows: skills tests pass on Windows
The two test temp roots kept `canonicalize`'s `\\?\` verbatim prefix, and the
kernel takes a verbatim path literally, so every `/`-joined path built under
them was an invalid filename. Strip it the way Node's `realpathSync` does.
The manifest, artifact and sibling-binary expectations hard-coded POSIX
separators for paths the product joins with the host's semantics; derive them
from `jsp::join` instead.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* windows: hook tests pass on Windows
Same verbatim-prefix strip on the test temp roots, plus expectations derived
from the helpers the product uses: cache keys and scan targets from
`jsp::join`, the config path in an admin message from the same relative form
`path.relative` renders, and the footer hints from `quote_command_arg`, which
deliberately switches to the double-quoted Windows form (#476 / #533). The
env lock no longer poisons the sibling tests when one of them fails.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* windows: html oracle goldens compare on Windows
The goldens pin the `<REPO>`-masked fixture path recorded on POSIX. Mask, then
render the remainder with `/` so a Windows checkout's backslashes are not read
as a finding difference. The goldens are untouched.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* windows: widen the live read-deadline test's margin
Timing only. The watchdog polls in 50ms steps against a ~15.6ms Windows system
timer while the crate's tests run in parallel, so the later request takes its
turn later there. The bound stays far under the 60s read timeout a
deadline-less read would hold the ticket for, so the test still distinguishes
the fix from the regression.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* windows: the request read deadline was not enforced on Windows
Windows does not unblock a `recv` already parked in the kernel when another
thread calls `shutdown` on the same socket, so the watchdog could not end a
silent connection's read and it held its turnstile place for the whole 60s
header timeout instead of the 10s deadline. Bound the read at the socket too,
which enforces the same deadline everywhere; the watchdog stays as the backstop
for a connection that trickles bytes without ever completing a request. POSIX
behavior is unchanged: the watchdog already closed the socket at the deadline.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* windows: hook tests derive the rest of the host path forms
The test temp helper's `write` returned a `PathBuf::join` result, which keeps
the `/` inside the relative part and so does not match what the hook resolves a
relative target to on Windows. Three more admin messages and the cache-root slug
pinned the POSIX spelling of paths the product renders with the host's
semantics (`path.resolve` also prefixes the current drive there).
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* windows: skills test fixtures name USERPROFILE, and the win32 quoted form
`os.homedir()` reads USERPROFILE on Windows, so a fixture home that named only
HOME sent the global installs into the runner's real profile. The Windows hook
command carries the JSON-quoted path, so a host path's backslashes arrive
escaped; derive the expectation instead of pinning the POSIX spelling.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* windows: check the oracle fixtures out with LF
A finding's snippet carries the scanned file's own bytes, and the goldens were
recorded from a POSIX checkout, so a CRLF checkout of a linked stylesheet reads
as a finding difference. The goldens are untouched.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* windows: check the grok global-install manifests as JSON
The Windows hook command carries the JSON-quoted launcher path, so the path's
backslashes are escaped once inside the command and again by the manifest file
itself. Read the manifest as JSON and look for either quoting form instead of
counting escaping layers in a raw substring match.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* npm shim: refuse a download with no verifiable sidecar
The skill launcher and `impeccable install` both fail closed when a
release binary's `.sha256` sidecar cannot be fetched or carries no hash:
they refuse rather than cache an unverified binary. The npm shim did not.
It only compared when a hash was present, so a 404, an empty sidecar, or
a truncated one all wrote the payload straight into
`~/.impeccable/bin/<version>/` and exec'd it.
It now refuses in the same cases, with wording that matches the launcher,
and writes nothing until the hash matches, so a refusal leaves the cache
dir empty. IMPECCABLE_BIN and the optional-dependency lookup are
untouched: neither downloads.
tests/cli-shim.test.mjs runs the real shim against a throwaway HTTP
server and covers missing, empty, and mismatched sidecars, plus the
matching-sidecar and IMPECCABLE_BIN paths. The two refusal cases fail
against the old shim.
Co-Authored-By: Claude Code <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* Oracle fixture: declare the vite plugin the web workspace imports
`live-workspaces/apps/web/vite.config.js` imports `@vitejs/plugin-react`
but the workspace's package.json listed only `vite`. No oracle case
installs or evaluates that config (the three `live-boot-workspaces-*`
cases stop at root resolution), so the fixture was never wrong at
runtime, only self-contradictory to read. Adding the devDependency keeps
the goldens byte-equal.
Co-Authored-By: Claude Code <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* Vectors: drop the 12,208 byte-identical repeat lines
The recorder deduplicated by arguments per run, not across runs, so the
frozen call snapshot arrived with 12,208 lines (43% of 28,266) that
repeat an earlier line byte for byte. Every one re-asserts what its first
occurrence already asserts, and `crates/core/tests/vectors.rs` replays
line by line with no count anywhere, so removing them changes nothing it
checks: the replay still reports 8,321 pass, 0 fail.
Duplicates were removed with `awk '!seen[$0]++'`, keeping first
occurrences and file order, and every changed file was checked to equal
that transform of its old contents. No line was added, reordered, or
rewritten, and no vector file gained or lost a distinct call. The tree
drops from 9.2 MB to 5.7 MB.
Co-Authored-By: Claude Code <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* Fix: restore the live overlay's disabledValues waivers in the engine
The JS engine applied value-level ignore waivers at the tail of
collectBrowserFindings: `_disabledValues` read the entries the live
overlay resolved for the page (skill/scripts/live-browser-ignores.js
sends them as config.disabledValues), and filtered the assembled
findings by the value each one reported, with design-system-color
compared by color value rather than by spelling so a hex waiver
suppressed a finding the browser reported as rgb(...). The Rust port
dropped that stage: `disabledValues` appeared nowhere in the workspace
or in browser-bundle, so a project entry like
[detector]
ignoreValues = [{ rule = "overused-font", value = "geist mono" }]
stopped reaching the overlay. The rules the CLI and the edit hook waive
kept drawing markers and counting toward the badge.
Restore it end to end:
* BrowserConfig gains `disabled_values`, parsed leniently so a
hand-edited __IMPECCABLE_CONFIG__ entry of the wrong shape is dropped
rather than failing the whole config, the way the JS filter did.
* The driver applies the waivers after every pass, so a rule pack's
findings are covered the same way the built-in ones are, honoring the
entries only in extension mode exactly as the JS read them. The
normalizer, the value extractor (including the rule that bounce-easing
without a direct ignoreValue offers no value) and the hex/rgb color
key are ported alongside it.
* collectConfigJson in the in-page bundle and configJson in the
offscreen bundle forward the field. The extension never sends it, so
its behavior is unchanged.
Coverage: two driver unit tests (suppression by font value, by hex
waiver across the rgb spelling, and the extension-mode gate; plus the
config parse and the normalizers), a skipScan test that pins the empty
shape for every stage the core produces, and
crates/wasm/tools/disabled-values-check.mjs, a browser-backed check
ported from the retired tests/detect-antipatterns-browser.test.mjs case
that the swap left without a replacement. Against the previous bundle it
fails on exactly the three waiver assertions and passes the skipScan
one, which is the shape of the regression.
Two related review findings were checked and are not defects. skipScan
is gated on extension mode in both the driver and the bundle, which is
what the JS did (index.mjs#skipScanActive), and the live overlay runs in
extension mode: live-browser.js sets `s.dataset.impeccableExtension` on
the injected /detect.js tag, and the overlay's whole detect toggle
travels over the postMessage loop that 50-scan.js installs only under
EXTENSION_MODE. The visual contrast stage is not leaking either:
collectBrowserFindingsAsync and scan() both consult skipScanActive(),
and the offscreen path skips its visual pass on config.skipScan.
The tracked live asset is regenerated (cargo xtask bundle). The oracle
replays with zero unreviewed differences: the new field defaults empty
and the filter is inert without it, and no CLI path sets extension mode.
AI-assisted change: implemented with Claude Code under maintainer
direction.
Co-Authored-By: Claude Code <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* Shim test: run from a staged copy and prove the download happened
The three fail-closed cases cleared IMPECCABLE_BIN and pointed
IMPECCABLE_HOME at a temp dir, but locate() prefers an installed
@impeccable/cli-<os>-<arch> before the cache or a download. Those
platform packages ship with every engine release and are a merge
prerequisite, so as soon as one is installed under the repo the cases
would resolve it and go green without fetching anything. Confirmed by
hand: with a platform package staged in node_modules, running the shim
against an unreachable download base still exits 0 from the package.
The shim now runs from a throwaway copy at <tmp>/cli/bin/cli.js beside a
copy of the repo's package.json, with no node_modules on the lookup path
above it, so require.resolve of the platform package fails the way it
does on a machine without the optional dependency. Production code is
unchanged; there is no test-only branch in the shim.
The fixture server also records every request now, and each download case
asserts the asset and sidecar URLs were actually requested, so a future
lookup shortcut fails loudly instead of passing on an untested path. A
sixth case installs a fake platform package next to the staged shim and
asserts the shim prefers it with the server untouched, which pins the
precedence the other cases depend on being absent.
Co-Authored-By: Claude Code <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* Live: the loader now hands off when the resume is the arrival
The overlay could sit in its generating shader over a DOM that already
held all three variants, and only a page refresh cleared it (#719).
The server's generation preflight runs live-wrap with
--defer-source-write, so the wrapper and every variant reach the DOM in a
single HMR batch. The deferred-wrapper scout is constructed at init and
the variant MutationObserver at Go; observer callbacks run in
construction order, so on that batch the scout resumes first and
resumeSession, not the observer, is the transition into CYCLING. It set
the state and the bar but never called hideShaderOverlay(), so the frozen
capture of the original stayed painted over the variants. It also
reported browser_resumed, which does not count as publication progress,
and then disconnected and re-created the observer, dropping the records
that observer had already queued for the same batch, so variants_ready
never fired at all.
resumeSession now finishes the same transition the observer does (shader
down, inline edit off, insert session finalized, params panel rebuilt)
and reports variants_ready when it already holds every variant. The
deferred scout names itself in the journal as
browser_resumed_deferred_wrapper, so the two resume paths are no longer
indistinguishable.
Wrapper resolution goes through findVariantsWrapper, which prefers a
wrapper that actually holds non-original variants. A target inside a
.map() renders one wrapper per item, and an agent that relocates the
wrapper out of the shared primitive live-wrap scaffolded leaves an empty
one behind; first match could pin either and strand the session at 0/N.
With zero or one match this is the querySelector it replaces.
Tests: waitForCycling now asserts the generating shader is gone once the
bar cycles, across every runtime fixture (it failed on vite8-react-plain
before this change and passes after), marked no-retry so the reload
recovery cannot hide it. Source-shape tests pin the transition, the
variants_ready report, and the wrapper preference.
Co-Authored-By: Claude Code <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* Live server: stop ends the process, SSE skips the mutation lane
Two Rust-only regressions found while investigating #719, both of which
can leave a tab waiting on a broadcast that never comes.
/stop ran shutdown() but never set shutting_down, and the accept loop
only breaks on that flag or a signal, so a stopped server kept its port
and kept answering while its server.json was already deleted. The next
`impeccable live` then booted a second server on another port and a tab
could reattach to the zombie. Node's shutdown() ended in process.exit(0).
The flag is now set after the response is written, so `stop` still reads
"stopping" instead of a reset connection, and the accept loop (already
non-blocking) exits on its next pass.
GET /events took a turnstile ticket and waited its turn before
registering, even though handle_sse releases that ticket two statements
later and needs no arrival ordering. A peer that stalls mid-request holds
the lane for the whole READ_REQUEST_DEADLINE, so a reconnecting stream
could sit unregistered for up to 10 seconds (measured 9.71s against 0.00s
on Node); broadcast is fire-and-forget, so a `done` landing in that
window reaches an empty client set and is gone. Registering early can
only make a stream see more broadcasts. The one cost is that the
connected frame's activeSessions snapshot may miss a mutation still in
flight, and the browser treats that snapshot as a hint. Preflights still
take a turn: answering those out of order reorders the POSTs the browser
issues behind them.
The route classification moved into releases_ticket_up_front so it can be
unit tested. tests/live-server-leak.test.mjs gains a guard that a stopped
server's pid is gone and its port is free.
Co-Authored-By: Claude Code <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* Live: the shader teardown can no longer race its own construction
The new cycling assertion caught a real defect on CI: vite8-react-insert
reached CYCLING with #impeccable-live-shader still painted over the page.
showShaderOverlay is async. It appends its canvas synchronously, then
awaits createImageBitmap and finishes the GL setup before it publishes
shaderState. hideShaderOverlay returned early on a null shaderState, so a
teardown that landed inside that window did nothing, and the construction
then published itself over a session that had already left GENERATING,
with no teardown left to run. The scroll tick kept repositioning it,
which is why the CI page.html shows the canvas sized from the capture
rect but styled to the cycling anchor.
Every teardown now bumps a shader epoch before it does anything else, and
a construction pins the epoch it owns and abandons its canvas (releasing
the GL context) at every point past an await and before any publish,
including both bitmap-fallback publishes. A teardown also drops a shader
node that no shaderState owns, so an already-orphaned canvas cannot
survive one.
Reproduced by widening the append-to-publish window: with a 400ms delay
after uiAppend, vite8-react-insert failed with the CI error and the probe
showed the teardown arriving at CYCLING with shaderState still null.
The same run passes with this change, as does a 1500ms window on insert
and plain. Locally that window is about 4ms, which is why it only showed
on a slower runner.
The four remaining setLiveState('CYCLING') sites that did not lower the
loader now do: the SSE done handler (the one route that can reach CYCLING
from GENERATING), the Svelte republish remount, and the two accept
failure recoveries.
The e2e assertion already waits up to 5s for the shader to clear, so it
was never racing a legitimate teardown; it is left as it is.
Co-Authored-By: Claude Code <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* Live: every active-session wrapper lookup goes through the resolver
Cursor Bugbot on #720: findVariantsWrapper alone was not enough.
resolveBarAnchor, the visible-variant element, mountedParameterCount,
readVisibleVariantFromDOM, showVariantInDOM, the source injection, and
the whole accept path still took the first [data-impeccable-variants]
match, so in the relocated-wrapper case Tune never bound and the bar kept
anchoring to the empty scaffold even after the resume reached CYCLING.
Thirteen call sites now resolve through findVariantsWrapper. The resolver
split in two so a missing id cannot silently widen the lookup to any
session: findVariantsWrapper(sessionId) returns null without an id, and
findAnyVariantsWrapper() is the entry point for the two resume paths that
have no id yet. Both share pickPopulatedVariantsWrapper, which is the old
querySelector whenever there are fewer than two matches.
Discard cleanup now hides every duplicate wrapper rather than the first,
since a target inside a `.map()` renders one per item and hiding one left
the rest of the discarded variants on screen.
What still takes a raw first match is deliberate: bare existence checks,
selector strings for stylesheets and observers (which want to cover every
match), querySelectorAll sweeps, the parsed source document, and the
Svelte component wrapper, which holds no variant children at all. The
source-shape test pins that exact set by name, so a new raw lookup fails
until it is either routed through the resolver or justified there.
Co-Authored-By: Claude Code <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* Live: a discard releases every wrapper it hid
Bugbot on #720: the non-restoreOriginal discard now hides every matching
wrapper, but the delayed fallback still released only the first
querySelector hit. A target inside a `.map()` renders one wrapper per
item, so the rest stayed at display:none and their original content never
came back on the static and missed-HMR flows that fallback exists for.
The hide, the existence checks, and the release now all speak about the
same set. discardedWrappers(sessionId) is the one place that collects it;
releaseDiscardedStaticWrappers takes the stylesheet down once and
releases each wrapper; releaseDiscardedStaticWrapper drops its sessionId
argument and just unwinds the node it is given. The HMR-ownership
decision still reads the first wrapper, which is fair: duplicates all
render from one source element, so ownership is uniform across them. The
reload branch is unchanged because a reload restores every original at
once.
Covered by a source-shape test rather than an e2e scenario:
hasFrameworkHmrOwnership is true for every React, Vue, and Svelte runtime
fixture, so all of them take the watcher path and none can reach the
static release. The existing framework-ownership guards in the same file
move to the new shape and keep their intent, including the one that says
only non-discard cleanup may blank the wrapper while waiting for HMR.
Co-Authored-By: Claude Code <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* Release: publish the npm platform packages in one command
bun run release:platform-packages downloads each engine-v<ENGINE_VERSION>
binary with its .sha256 sidecar (required; nothing unverified is
published), stages the package from cli/platform-packages/<target> with
the version stamped, the executable at bin/ and the repo LICENSE, and
runs npm publish --access public. Targets already on the registry are
skipped so a re-run resumes after a partial failure. Preconditions:
package.json pins equal ENGINE_VERSION and npm is logged in.
Co-Authored-By: Claude Code <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* release-engine: pin checkout, upload-artifact and download-artifact at v7
The v4 pins target Node 20, which the runner now deprecates and forces
onto Node 24 with a warning on every step. The rest of the workflows
already use v7.
Co-Authored-By: Claude Code <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* Tests: make the temp-dir helpers unique under a coarse clock
Windows' system clock is coarse enough that two parallel tests could get
the same pid-plus-nanoseconds directory name and then remove each
other's files (rust-windows: close_verb_round_trip_and_ownership,
NotFound). A per-process counter is appended to the name.
Co-Authored-By: Claude Code <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
* Tests: declare the temp-dir counter in the hook cache-root tests
The previous commit referenced TMP_SEQ there without defining it.
Co-Authored-By: Claude Code <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vau2X53xGTjjTCXWMVBoNY
---------
Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,313 @@
|
||||
//! Section 4 (`resolveBackground` family) in browser mode
|
||||
//! (`DETECTOR_IS_BROWSER === true`; the static-only branches — inline
|
||||
//! `style=""` peeks and customPropMap resolution — are not reachable here
|
||||
//! and are not ported). See browser/mod.rs.
|
||||
|
||||
use super::dom::{Dom, ElId};
|
||||
use crate::color::{
|
||||
composite_color_over, is_no_paint_color_value, parse_any_color, parse_gradient_colors,
|
||||
parse_rgb, split_top_level_commas, Rgba,
|
||||
};
|
||||
use crate::js;
|
||||
use once_cell::sync::Lazy;
|
||||
use regex::Regex;
|
||||
|
||||
macro_rules! re {
|
||||
($name:ident, $pat:expr) => {
|
||||
static $name: Lazy<Regex> = Lazy::new(|| Regex::new(&$pat).expect(stringify!($name)));
|
||||
};
|
||||
}
|
||||
|
||||
// JS `/gradient/i`, `/url\s*\(/i`, `/gradient\s*\(/i`, `/^\s*url\s*\(/i`,
|
||||
// `/^currentcolor$/i`: ASCII case folding (`ci`) and the JS `\s` set (`WS`).
|
||||
re!(GRADIENT_RE, js::ci("gradient"));
|
||||
re!(URL_RE, format!("{}{}*\\(", js::ci("url"), js::WS));
|
||||
re!(GRADIENT_PAREN_RE, format!("{}{}*\\(", js::ci("gradient"), js::WS));
|
||||
re!(URL_LEADING_RE, format!("^{}*{}{}*\\(", js::WS, js::ci("url"), js::WS));
|
||||
re!(CURRENTCOLOR_RE, format!("^{}$", js::ci("currentcolor")));
|
||||
|
||||
/// JS `{ color, unresolved }` from resolveBackgroundInfo.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Default)]
|
||||
pub struct BackgroundInfo {
|
||||
pub color: Option<Rgba>,
|
||||
pub unresolved: bool,
|
||||
}
|
||||
|
||||
/// JS `parseRgb(x) || parseAnyColor(x)`.
|
||||
fn parse_rgb_or_any(value: &str) -> Option<Rgba> {
|
||||
parse_rgb(Some(value)).or_else(|| parse_any_color(Some(value)))
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#readOwnBackgroundColor(el, computedStyle) — in the browser
|
||||
/// `DETECTOR_IS_BROWSER` short-circuits before the inline-shorthand peek, so
|
||||
/// this is the computed-style parse alone.
|
||||
pub fn read_own_background_color(dom: &dyn Dom, el: ElId) -> Option<Rgba> {
|
||||
parse_rgb_or_any(&dom.style(el, "backgroundColor"))
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#readCascadeBackgroundColor(current, style, customPropMap)
|
||||
/// — browser branch: computed style only.
|
||||
fn read_cascade_background_color(dom: &dyn Dom, el: ElId) -> Option<Rgba> {
|
||||
parse_rgb_or_any(&dom.style(el, "backgroundColor"))
|
||||
}
|
||||
|
||||
/// JS `bg && bg.a > 0.1` — `bg.a` is `undefined` (never for parsed
|
||||
/// colors, but keep JS `undefined > 0.1 === false`).
|
||||
fn alpha_gt(bg: &Rgba, t: f64) -> bool {
|
||||
match bg.a {
|
||||
Some(a) => a > t,
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#resolveBackgroundInfo(el, win, customPropMap) in browser mode.
|
||||
pub fn resolve_background_info(dom: &dyn Dom, el: ElId) -> BackgroundInfo {
|
||||
let mut current = Some(el);
|
||||
let mut overlays: Vec<Rgba> = Vec::new();
|
||||
let flatten = |overlays: &Vec<Rgba>, base: Rgba| -> Rgba {
|
||||
let mut acc = base;
|
||||
for o in overlays.iter().rev() {
|
||||
acc = composite_color_over(o, &acc);
|
||||
}
|
||||
acc
|
||||
};
|
||||
while let Some(cur) = current {
|
||||
let bg_image = dom.style(cur, "backgroundImage");
|
||||
let has_gradient_or_url = !bg_image.is_empty()
|
||||
&& bg_image != "none"
|
||||
&& (GRADIENT_RE.is_match(&bg_image) || URL_RE.is_match(&bg_image));
|
||||
|
||||
let mut bg = read_cascade_background_color(dom, cur);
|
||||
|
||||
let bg_color_raw = dom.style(cur, "backgroundColor");
|
||||
if (bg.is_none() || bg.map_or(false, |b| b.alpha_or_one() < 0.1))
|
||||
&& CURRENTCOLOR_RE.is_match(js::trim(&bg_color_raw))
|
||||
{
|
||||
// JS: `bg.a < 0.1` with `a` undefined is false; alpha_or_one keeps
|
||||
// that (undefined never < 0.1 → treat as 1).
|
||||
let color = dom.style(cur, "color");
|
||||
bg = parse_rgb(Some(&color)).or_else(|| parse_any_color(Some(&color)));
|
||||
}
|
||||
|
||||
match bg {
|
||||
Some(b) if alpha_gt(&b, 0.1) => {
|
||||
if b.a.map_or(false, |a| a >= 0.99) {
|
||||
return BackgroundInfo {
|
||||
color: Some(flatten(&overlays, b)),
|
||||
unresolved: false,
|
||||
};
|
||||
}
|
||||
overlays.push(b);
|
||||
}
|
||||
None if !is_no_paint_color_value(Some(&bg_color_raw)) => {
|
||||
return BackgroundInfo {
|
||||
color: None,
|
||||
unresolved: true,
|
||||
};
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
if has_gradient_or_url {
|
||||
let layers = split_top_level_commas(&bg_image);
|
||||
let top_paint_layer = layers
|
||||
.iter()
|
||||
.find(|layer| GRADIENT_PAREN_RE.is_match(layer) || URL_RE.is_match(layer));
|
||||
let gradient_on_top = match top_paint_layer {
|
||||
Some(layer) => {
|
||||
GRADIENT_PAREN_RE.is_match(layer) && !URL_LEADING_RE.is_match(layer)
|
||||
}
|
||||
None => false,
|
||||
};
|
||||
if !gradient_on_top {
|
||||
return BackgroundInfo {
|
||||
color: None,
|
||||
unresolved: true,
|
||||
};
|
||||
}
|
||||
let top = top_paint_layer.expect("gradient_on_top implies a layer");
|
||||
let url_beneath = layers
|
||||
.iter()
|
||||
.any(|layer| layer != top && URL_RE.is_match(layer));
|
||||
if url_beneath {
|
||||
let top_stops = parse_gradient_colors(Some(top));
|
||||
let provably_opaque =
|
||||
!top_stops.is_empty() && top_stops.iter().all(|s| s.alpha_or_one() >= 0.99);
|
||||
if !provably_opaque {
|
||||
return BackgroundInfo {
|
||||
color: None,
|
||||
unresolved: true,
|
||||
};
|
||||
}
|
||||
}
|
||||
return BackgroundInfo {
|
||||
color: None,
|
||||
unresolved: false,
|
||||
};
|
||||
}
|
||||
current = dom.parent(cur);
|
||||
}
|
||||
BackgroundInfo {
|
||||
color: Some(flatten(&overlays, Rgba::new(255.0, 255.0, 255.0, 1.0))),
|
||||
unresolved: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#resolveBackground(el, win, customPropMap)
|
||||
pub fn resolve_background(dom: &dyn Dom, el: ElId) -> Option<Rgba> {
|
||||
resolve_background_info(dom, el).color
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#compositeGradientStops(stops, gradientEl, win, customPropMap)
|
||||
fn composite_gradient_stops(dom: &dyn Dom, stops: Vec<Rgba>, gradient_el: ElId) -> Option<Vec<Rgba>> {
|
||||
let has_alpha = stops.iter().any(|s| s.alpha_or_one() < 0.99);
|
||||
if !has_alpha {
|
||||
return Some(stops);
|
||||
}
|
||||
let base_el = dom.parent(gradient_el).unwrap_or(gradient_el);
|
||||
let base = resolve_background(dom, base_el);
|
||||
let mut out = Vec::new();
|
||||
for s in stops {
|
||||
let a = s.alpha_or_one();
|
||||
if a >= 0.99 {
|
||||
out.push(s);
|
||||
continue;
|
||||
}
|
||||
if let Some(b) = base {
|
||||
out.push(composite_color_over(&s, &b));
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#resolveGradientStops(el, win, customPropMap) in browser mode.
|
||||
pub fn resolve_gradient_stops(dom: &dyn Dom, el: ElId) -> Option<Vec<Rgba>> {
|
||||
let mut current = Some(el);
|
||||
let mut overlays: Vec<Rgba> = Vec::new();
|
||||
while let Some(cur) = current {
|
||||
let bg_image = dom.style(cur, "backgroundImage");
|
||||
if !bg_image.is_empty() && bg_image != "none" && URL_RE.is_match(&bg_image) {
|
||||
return None;
|
||||
}
|
||||
let mut stops: Option<Vec<Rgba>> = None;
|
||||
if !bg_image.is_empty() && bg_image != "none" && GRADIENT_RE.is_match(&bg_image) {
|
||||
let parsed = parse_gradient_colors(Some(&bg_image));
|
||||
if !parsed.is_empty() {
|
||||
stops = Some(parsed);
|
||||
}
|
||||
}
|
||||
if let Some(stops) = stops {
|
||||
let composited = composite_gradient_stops(dom, stops, cur);
|
||||
let Some(composited) = composited else { return None };
|
||||
if overlays.is_empty() {
|
||||
return Some(composited);
|
||||
}
|
||||
return Some(
|
||||
composited
|
||||
.into_iter()
|
||||
.map(|stop| {
|
||||
let mut acc = stop;
|
||||
for o in overlays.iter().rev() {
|
||||
acc = composite_color_over(o, &acc);
|
||||
}
|
||||
acc
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
let bg = read_cascade_background_color(dom, cur);
|
||||
if let Some(b) = bg {
|
||||
if alpha_gt(&b, 0.1) {
|
||||
if b.a.map_or(false, |a| a >= 0.99) {
|
||||
return None;
|
||||
}
|
||||
overlays.push(b);
|
||||
}
|
||||
}
|
||||
current = dom.parent(cur);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::browser::fake_dom::FakeDom;
|
||||
|
||||
#[test]
|
||||
fn opaque_ancestor_wins_and_translucent_overlays_flatten() {
|
||||
let mut d = FakeDom::new();
|
||||
let (html, body) = d.with_page();
|
||||
d.set_style(html, "backgroundColor", "rgba(0, 0, 0, 0)");
|
||||
d.set_style(html, "backgroundImage", "none");
|
||||
d.set_style(body, "backgroundColor", "rgb(0, 0, 0)");
|
||||
d.set_style(body, "backgroundImage", "none");
|
||||
let card = d.add(Some(body), "div");
|
||||
d.set_style(card, "backgroundColor", "rgba(255, 255, 255, 0.5)");
|
||||
d.set_style(card, "backgroundImage", "none");
|
||||
let info = resolve_background_info(&d, card);
|
||||
assert!(!info.unresolved);
|
||||
assert_eq!(info.color, Some(Rgba::new(128.0, 128.0, 128.0, 1.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transparent_chain_falls_back_to_white_and_url_layer_abstains() {
|
||||
let mut d = FakeDom::new();
|
||||
let (html, body) = d.with_page();
|
||||
for e in [html, body] {
|
||||
d.set_style(e, "backgroundColor", "rgba(0, 0, 0, 0)");
|
||||
d.set_style(e, "backgroundImage", "none");
|
||||
}
|
||||
let p = d.add(Some(body), "p");
|
||||
d.set_style(p, "backgroundColor", "rgba(0, 0, 0, 0)");
|
||||
d.set_style(p, "backgroundImage", "none");
|
||||
assert_eq!(resolve_background(&d, p), Some(Rgba::new(255.0, 255.0, 255.0, 1.0)));
|
||||
d.set_style(body, "backgroundImage", "url(\"photo.png\")");
|
||||
let info = resolve_background_info(&d, p);
|
||||
assert!(info.unresolved && info.color.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_on_top_yields_stops_and_unparseable_color_abstains() {
|
||||
let mut d = FakeDom::new();
|
||||
let (html, body) = d.with_page();
|
||||
d.set_style(html, "backgroundColor", "rgba(0, 0, 0, 0)");
|
||||
d.set_style(html, "backgroundImage", "none");
|
||||
d.set_style(body, "backgroundColor", "rgba(0, 0, 0, 0)");
|
||||
d.set_style(body, "backgroundImage", "linear-gradient(rgb(10, 20, 30), rgb(40, 50, 60))");
|
||||
let p = d.add(Some(body), "p");
|
||||
d.set_style(p, "backgroundColor", "rgba(0, 0, 0, 0)");
|
||||
d.set_style(p, "backgroundImage", "none");
|
||||
let info = resolve_background_info(&d, p);
|
||||
assert!(!info.unresolved && info.color.is_none());
|
||||
let stops = resolve_gradient_stops(&d, p).unwrap();
|
||||
assert_eq!(stops.len(), 2);
|
||||
assert_eq!(stops[0], Rgba::new(10.0, 20.0, 30.0, 1.0));
|
||||
d.set_style(p, "backgroundColor", "color(display-p3 1 0 0 / 0.5)");
|
||||
// JS parseAnyColor may or may not read display-p3; whatever it does,
|
||||
// an unreadable, non-no-paint value abstains.
|
||||
let info = resolve_background_info(&d, p);
|
||||
if parse_any_color(Some("color(display-p3 1 0 0 / 0.5)")).is_none() {
|
||||
assert!(info.unresolved);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn currentcolor_background_paints_with_text_color() {
|
||||
let mut d = FakeDom::new();
|
||||
let (html, body) = d.with_page();
|
||||
for e in [html, body] {
|
||||
d.set_style(e, "backgroundColor", "rgba(0, 0, 0, 0)");
|
||||
d.set_style(e, "backgroundImage", "none");
|
||||
}
|
||||
let chip = d.add(Some(body), "span");
|
||||
d.set_style(chip, "backgroundColor", "currentcolor");
|
||||
d.set_style(chip, "backgroundImage", "none");
|
||||
d.set_style(chip, "color", "rgb(1, 2, 3)");
|
||||
assert_eq!(resolve_background(&d, chip), Some(Rgba::new(1.0, 2.0, 3.0, 1.0)));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,91 @@
|
||||
//! The in-page (browser) rule set, ported from the DOM adapters of
|
||||
//! `cli/engine/rules/checks.mjs` (Sections 4-6, the `*DOM` functions) and
|
||||
//! the driver in `cli/engine/browser/injected/index.mjs`. Everything here is
|
||||
//! rule logic written against the [`dom::Dom`] probe trait; the JavaScript
|
||||
//! left in the bundle only implements that trait, marshals JSON, and draws
|
||||
//! the overlay UI.
|
||||
//!
|
||||
//! The probe trait itself, its snapshot implementation, the selector engine,
|
||||
//! the test fake and the plain-data types live in
|
||||
//! `impeccable_foundation::browser`; they are re-exported here under the
|
||||
//! paths callers already use.
|
||||
//!
|
||||
//! Module map (one JS region each, so parallel work does not collide):
|
||||
//!
|
||||
//! - `dom`: the [`dom::Dom`] trait, `ElId`, `Rect`, shared helpers.
|
||||
//! - `snapshot`: [`snapshot::SnapshotDom`], the trait over a serialized page
|
||||
//! (the extension's CSP-proof path), plus the one-shot findings run that
|
||||
//! drives the checks below; `selector`: the Chrome-flavored selector
|
||||
//! engine it matches with.
|
||||
//! - `fake_dom`: a table-driven fake for unit tests (test builds only).
|
||||
//! - `background`: Section 4 in browser mode — `readOwnBackgroundColor`,
|
||||
//! `readCascadeBackgroundColor`, `resolveBackgroundInfo`,
|
||||
//! `resolveBackground`, `resolveGradientStops`, `compositeGradientStops`.
|
||||
//! - `element_checks`: the per-element adapters of Section 5 —
|
||||
//! `isTabContextElement`, `isStatusContextElement`, `checkElementBordersDOM`,
|
||||
//! `checkElementPseudoStripeDOM`, `readPseudoSurfaceDOM`,
|
||||
//! `checkElementColorsDOM`, `checkElementIconTileDOM`,
|
||||
//! `checkElementItalicSerifDOM`, `domAccentDashPseudo`,
|
||||
//! `checkElementHeroEyebrowDOM`, `checkElementMotionDOM`,
|
||||
//! `checkElementGlowDOM`, `checkElementAIPaletteDOM`,
|
||||
//! `elementGradientValue`, `spotlightLabel`, `checkElementRadialSpotlightDOM`,
|
||||
//! `checkElementOversizedH1DOM`, `checkElementGptBorderShadowDOM`,
|
||||
//! `classSelector`, `positionedChild*`, `clippingContainerIsIntentionalViewport`,
|
||||
//! `elementRect`, `positionedChildEscapesClip`, `checkClippedOverflow`,
|
||||
//! `checkElementClippedOverflowDOM`, `isRenderedForBrowserRule`,
|
||||
//! `checkElementTextOverflowDOM`, `keyframesToggleVisibilityDOM`,
|
||||
//! `checkElementBlinkingCursorDOM`, `effectiveOpacityDOM`.
|
||||
//! - `quality`: `checkQuality` (browser branches included),
|
||||
//! `checkElementQualityDOM`, `hasVisibleBackgroundBoundary`,
|
||||
//! `hasMeaningfulDirectText`, `textDescendantsFlushSides`,
|
||||
//! `isVisuallyHidden`, `isNonRenderedText`, `checkPageQualityFromDoc`,
|
||||
//! `checkPageQualityDOM`.
|
||||
//! - `page_checks`: Section 6 browser page-level checks — `checkTypography`,
|
||||
//! `isCardLikeDOM`, `checkLayout`, `checkHeadingRhythmDOM`,
|
||||
//! `checkCreamPalette` (browser path), `measureHiddenTextDOM`,
|
||||
//! `checkEdgeFlushCardsDOM`, `isOpaqueDecoratedBox` (in core measures),
|
||||
//! `isLayeredElement`, `elementDirectText`, `isPaintedForOcclusion`,
|
||||
//! `checkTextOcclusionDOM`, `checkFirstViewportColumnOverflowDOM`.
|
||||
//! - `text_collectors`: `cleanInlineText`, `isKickerCardContext`,
|
||||
//! `kickerHeadingLevel`, `collectKickerCandidates`,
|
||||
//! `checkKickerAboveHeadingDOM`, `collectNumberedSectionLabelCandidates`,
|
||||
//! `checkNumberedSectionLabelsDOM`, `checkEmDashOveruseDOM`,
|
||||
//! `collectRepeatedContainerTextFindings`, `checkRepeatedContainerTextDOM`.
|
||||
//! - `driver`: index.mjs — `scopedIgnoreActive`, `collectBrowserFindings`
|
||||
//! (element loop, page-level passes, html-pattern scoping, pulsing-dot
|
||||
//! promotion), the design-system checks, `serializeFindings`,
|
||||
//! `generateSelector`/`buildSelectorSegment`/`isLikelyHashedClass`,
|
||||
//! `isElementHidden`, `addVisualContrastResult`'s decision.
|
||||
//! - `visual`: the visual-contrast subsystem's decisions —
|
||||
//! `collectVisualContrastReasons`, `collectVisualContrastCandidates`,
|
||||
//! `blendRgba`, `pickWorstContrastColor`, `textSamplePoints`,
|
||||
//! `parsePositionToken/Pair`, `resolvePaintedImageRect`,
|
||||
//! `resolveObjectImageRect`, `pointToImageSource`, `firstCssUrl`,
|
||||
//! `getLayerValue`, the candidate-analysis finalization. Its plain-data
|
||||
//! plans and rects are shared. The async pixel sampling (Image loading,
|
||||
//! canvas draws) stays JS and feeds these.
|
||||
//!
|
||||
//! Porting rules are the crate's usual ones (see docs/PORTING-GUIDE.md):
|
||||
//! JS number/string semantics through `crate::js`, field order preserved,
|
||||
//! bugs ported, `// JS-PARITY:` where it looks odd. Every function carries a
|
||||
//! `/// JS: <file>#<name>` doc comment.
|
||||
|
||||
pub use impeccable_foundation::browser::dom;
|
||||
pub use impeccable_foundation::browser::selector;
|
||||
|
||||
#[cfg(any(test, feature = "fake-dom"))]
|
||||
pub use impeccable_foundation::browser::fake_dom;
|
||||
|
||||
pub mod background;
|
||||
pub mod driver;
|
||||
pub mod element_checks;
|
||||
pub mod page_checks;
|
||||
pub mod quality;
|
||||
pub mod snapshot;
|
||||
pub mod text_collectors;
|
||||
pub mod visual;
|
||||
|
||||
pub use dom::{Dom, ElId, Rect};
|
||||
pub use impeccable_foundation::browser::{
|
||||
BrowserConfig, BrowserFinding, DisabledValue, ElFinding, FindingGroup,
|
||||
};
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,925 @@
|
||||
//! `checkQuality` and its browser adapters from `checks.mjs` Section 5:
|
||||
//! `checkQuality` (every branch, including the rect-gated ones the static
|
||||
//! engine never reaches), `checkElementQualityDOM`,
|
||||
//! `hasVisibleBackgroundBoundary`, `hasMeaningfulDirectText`,
|
||||
//! `textDescendantsFlushSides`, `isVisuallyHidden`, `isNonRenderedText`,
|
||||
//! `checkPageQualityFromDoc`, `checkPageQualityDOM`.
|
||||
|
||||
#![allow(unused_imports)]
|
||||
use super::dom::{
|
||||
closest_or_none, direct_text, has_direct_text_longer_than, matches_or_false, pf0, safe_id,
|
||||
style_px, tag_lower, Dom, ElId, Rect,
|
||||
};
|
||||
use super::{BrowserConfig, BrowserFinding};
|
||||
use crate::checks::measures::{colors_nearly_match, css_color_is_transparent, resolve_length_px};
|
||||
use crate::checks::rules::RuleHit;
|
||||
use crate::checks::text_rules::{
|
||||
NON_RENDERED_TAGS, QUALITY_TEXT_TAGS, SR_ONLY_SELECTOR, TEXT_EDGE_TAGS,
|
||||
};
|
||||
use crate::js::{self, math_round, number_to_string, parse_float, to_fixed};
|
||||
use crate::js_ext_b::{slice_utf16_prefix, utf16_len};
|
||||
use once_cell::sync::Lazy;
|
||||
use regex::Regex;
|
||||
|
||||
macro_rules! re {
|
||||
($name:ident, $pat:expr) => {
|
||||
static $name: Lazy<Regex> = Lazy::new(|| Regex::new(&$pat).expect(stringify!($name)));
|
||||
};
|
||||
}
|
||||
|
||||
re!(WS_RE, format!("{}+", js::WS));
|
||||
// JS `/url\(/i` in checkQuality's buried-raster branch.
|
||||
re!(QUALITY_RASTER_URL_RE, format!(r"{}\(", js::ci("url")));
|
||||
re!(CLIP_RECT_RE, format!(r"rect\({}*0", js::WS));
|
||||
re!(
|
||||
CLIP_INSET_RE,
|
||||
format!(r"inset\({}*(?:50%|99|100%)", js::WS)
|
||||
);
|
||||
re!(OUTLINE_W_RE, r"([0-9]+(?:\.[0-9]+)?)\s*px");
|
||||
re!(
|
||||
OUTLINE_STYLE_RE,
|
||||
r"(?-u:\b)(solid|dashed|dotted|double|groove|ridge|inset|outset)(?-u:\b)"
|
||||
);
|
||||
re!(
|
||||
OUTLINE_COLOR_RE,
|
||||
format!(r"(rgba?\([^)]+\)|#[0-9a-fA-F]{{3,8}}|[a-zA-Z]+){}*$", js::WS)
|
||||
);
|
||||
|
||||
/// JS `s.replace(/\s+/g, ' ')`.
|
||||
pub fn collapse_ws(s: &str) -> String {
|
||||
WS_RE.replace_all(s, " ").into_owned()
|
||||
}
|
||||
|
||||
const FLUSH_SKIP_TAGS: &[&str] = &[
|
||||
"HTML", "BODY", "MAIN", "HEADER", "FOOTER", "NAV", "ARTICLE", "ASIDE", "BUTTON", "A", "LABEL",
|
||||
"SUMMARY", "CODE", "PRE", "INPUT", "TEXTAREA", "SELECT", "FORM", "FIGURE", "TABLE", "TBODY",
|
||||
"THEAD", "TR", "TD", "TH",
|
||||
];
|
||||
|
||||
const TINY_TEXT_UI_CONTEXT: &str = "button, a, label, summary, pre, [role=\"button\"], [role=\"link\"], [role=\"tab\"], [role=\"menuitem\"], [role=\"option\"], nav, footer, [aria-hidden=\"true\"], [class*=\"badge\" i], [class*=\"caption\" i], [class*=\"chip\" i], [class*=\"code\" i], [class*=\"console\" i], [class*=\"diff\" i], [class*=\"label\" i], [class*=\"meta\" i], [class*=\"mock\" i], [class*=\"pill\" i], [class*=\"preview\" i], [class*=\"tag\" i], [class*=\"terminal\" i], [class*=\"writes\" i]";
|
||||
const EXEMPT_CONTEXT: &str = "pre, code, kbd, samp, var, svg, [aria-hidden=\"true\"], [class*=\"terminal\" i], [class*=\"console\" i], [class*=\"code\" i], [class*=\"mock\" i], [class*=\"editor\" i], [class*=\"syntax\" i], [class*=\"diff\" i]";
|
||||
const INTERACTIVE: &str = "a[href], button, summary, label, select, textarea, [role=\"button\"], [role=\"link\"], [role=\"tab\"], [role=\"menuitem\"], [role=\"menuitemcheckbox\"], [role=\"menuitemradio\"], [role=\"option\"], [role=\"checkbox\"], [role=\"radio\"], [role=\"switch\"], [role=\"treeitem\"], [tabindex]";
|
||||
const FURNITURE: &str = "nav, [role=\"navigation\"], td, th, [role=\"gridcell\"], [role=\"cell\"], caption, figcaption, dt, dd, footer, [class*=\"meta\" i], [class*=\"label\" i], [class*=\"badge\" i], [class*=\"chip\" i], [class*=\"pill\" i], [class*=\"tag\" i], [class*=\"kicker\" i], [class*=\"eyebrow\" i], [class*=\"breadcrumb\" i], [class*=\"timestamp\" i], [class*=\"category\" i], [class*=\"caption\" i], [class*=\"nav\" i]";
|
||||
const SMALLPRINT: &str = "small, footer, [class*=\"legal\" i], [class*=\"copyright\" i], [class*=\"fineprint\" i], [class*=\"fine-print\" i], [class*=\"smallprint\" i], [class*=\"small-print\" i], [class*=\"disclaimer\" i], [class*=\"disclosure\" i], [class*=\"footnote\" i]";
|
||||
const TEXT_EDGE_QUERY: &str =
|
||||
"a, button, code, dd, dt, figcaption, h1, h2, h3, h4, h5, h6, li, p, pre, span, td, th";
|
||||
|
||||
/// JS `(el.matches && el.matches(sel)) || (el.closest && el.closest(sel))`.
|
||||
fn matches_or_closest(dom: &dyn Dom, el: ElId, sel: &str) -> bool {
|
||||
matches_or_false(dom, el, sel) || closest_or_none(dom, el, sel).is_some()
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#hasVisibleBackgroundBoundary(style, el, win) — browser:
|
||||
/// `style` is `el`'s own computed style, `win` the live window.
|
||||
pub fn has_visible_background_boundary(dom: &dyn Dom, el: ElId) -> bool {
|
||||
let bg = dom.style(el, "backgroundColor");
|
||||
if css_color_is_transparent(Some(&bg)) {
|
||||
return false;
|
||||
}
|
||||
let mut parent = dom.parent(el);
|
||||
while let Some(p) = parent {
|
||||
let parent_bg = dom.style(p, "backgroundColor");
|
||||
if !css_color_is_transparent(Some(&parent_bg)) {
|
||||
return !colors_nearly_match(Some(&bg), Some(&parent_bg));
|
||||
}
|
||||
parent = dom.parent(p);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#hasMeaningfulDirectText(node)
|
||||
pub fn has_meaningful_direct_text(dom: &dyn Dom, el: ElId) -> bool {
|
||||
has_direct_text_longer_than(dom, el, 4)
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#textDescendantsFlushSides(el, rect) → [top, right, bottom, left]
|
||||
pub fn text_descendants_flush_sides(dom: &dyn Dom, el: ElId, rect: &Rect) -> [bool; 4] {
|
||||
let mut flush = [false; 4];
|
||||
const TEXT_EDGE_THRESHOLD: f64 = 4.0;
|
||||
let candidates = dom.query_all(Some(el), TEXT_EDGE_QUERY).unwrap_or_default();
|
||||
for node in candidates {
|
||||
let tag_name = dom.tag_name(node);
|
||||
if !TEXT_EDGE_TAGS.contains(&tag_name.as_str()) || !has_meaningful_direct_text(dom, node) {
|
||||
continue;
|
||||
}
|
||||
let nr = dom.rect(node);
|
||||
if nr.width <= 0.0 || nr.height <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
if nr.bottom < rect.top || nr.top > rect.bottom || nr.right < rect.left || nr.left > rect.right {
|
||||
continue;
|
||||
}
|
||||
if nr.top - rect.top <= TEXT_EDGE_THRESHOLD {
|
||||
flush[0] = true;
|
||||
}
|
||||
if rect.right - nr.right <= TEXT_EDGE_THRESHOLD {
|
||||
flush[1] = true;
|
||||
}
|
||||
if rect.bottom - nr.bottom <= TEXT_EDGE_THRESHOLD {
|
||||
flush[2] = true;
|
||||
}
|
||||
if nr.left - rect.left <= TEXT_EDGE_THRESHOLD {
|
||||
flush[3] = true;
|
||||
}
|
||||
}
|
||||
flush
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#isVisuallyHidden(el, style)
|
||||
pub fn is_visually_hidden(dom: &dyn Dom, el: ElId) -> bool {
|
||||
if matches_or_closest(dom, el, SR_ONLY_SELECTOR) {
|
||||
return true;
|
||||
}
|
||||
let pos = dom.style(el, "position");
|
||||
if pos == "absolute" || pos == "fixed" {
|
||||
let clip = dom.style(el, "clip");
|
||||
let clip_path = {
|
||||
let a = dom.style(el, "clipPath");
|
||||
if !a.is_empty() {
|
||||
a
|
||||
} else {
|
||||
let b = dom.style(el, "webkitClipPath");
|
||||
if !b.is_empty() {
|
||||
b
|
||||
} else {
|
||||
dom.style(el, "clip-path")
|
||||
}
|
||||
}
|
||||
};
|
||||
if CLIP_RECT_RE.is_match(&clip) || CLIP_INSET_RE.is_match(&clip_path) {
|
||||
return true;
|
||||
}
|
||||
let w = parse_float(&dom.style(el, "width"));
|
||||
let h = parse_float(&dom.style(el, "height"));
|
||||
let overflow = dom.style(el, "overflow");
|
||||
if (w == 1.0 || h == 1.0) && (overflow == "hidden" || overflow == "clip") {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#isNonRenderedText(el, tag, style)
|
||||
pub fn is_non_rendered_text(dom: &dyn Dom, el: ElId, tag: &str) -> bool {
|
||||
let t = js::to_lower_case(tag);
|
||||
if NON_RENDERED_TAGS.contains(&t.as_str()) {
|
||||
return true;
|
||||
}
|
||||
if closest_or_none(dom, el, "head").is_some() {
|
||||
return true;
|
||||
}
|
||||
if dom.style(el, "display") == "none" {
|
||||
return true;
|
||||
}
|
||||
let vis = dom.style(el, "visibility");
|
||||
if vis == "hidden" || vis == "collapse" {
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Inputs of `checkQuality` as the browser adapter builds them.
|
||||
pub struct QualityInput {
|
||||
pub el: ElId,
|
||||
pub tag: String,
|
||||
pub has_direct_text: bool,
|
||||
pub text_len: usize,
|
||||
pub font_size: f64,
|
||||
pub line_height_px: Option<f64>,
|
||||
pub letter_spacing_px: Option<f64>,
|
||||
pub rect: Rect,
|
||||
pub line_max: f64,
|
||||
pub viewport_width: f64,
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#checkQuality(opts), browser adapter inputs (`rect` set,
|
||||
/// `win` = window).
|
||||
pub fn check_quality(dom: &dyn Dom, q: &QualityInput) -> Vec<RuleHit> {
|
||||
let el = q.el;
|
||||
let tag = q.tag.as_str();
|
||||
let font_size = q.font_size;
|
||||
let text_len = q.text_len;
|
||||
let rect = &q.rect;
|
||||
let line_max = q.line_max;
|
||||
let viewport_width = q.viewport_width;
|
||||
let has_direct_text = q.has_direct_text;
|
||||
let mut findings: Vec<RuleHit> = Vec::new();
|
||||
|
||||
let el_id = safe_id(dom, el);
|
||||
if el_id.starts_with("claude-") || el_id.starts_with("cic-") {
|
||||
return findings;
|
||||
}
|
||||
|
||||
let st = |k: &str| dom.style(el, k);
|
||||
let spx = |k: &str| style_px(dom, el, k);
|
||||
|
||||
// A raster (<img>, or an element with a background url) at near-zero
|
||||
// opacity never reaches the screen: the produced material ships as a
|
||||
// compliance token. The CSS-text scan catches the stylesheet form; this
|
||||
// catches computed opacity on the element itself (both engines).
|
||||
{
|
||||
let op = parse_float(&st("opacity"));
|
||||
if op.is_finite() && op < 0.15 && op >= 0.0 {
|
||||
let bg = st("backgroundImage");
|
||||
if tag == "img" || QUALITY_RASTER_URL_RE.is_match(&bg) {
|
||||
let label = if tag == "img" {
|
||||
dom.attr(el, "alt").unwrap_or_default()
|
||||
} else {
|
||||
slice_utf16_prefix(js::trim(&dom.text_content(el)), 40)
|
||||
};
|
||||
findings.push(RuleHit::new(
|
||||
"buried-raster",
|
||||
format!(
|
||||
"{} at opacity {}{}",
|
||||
if tag == "img" { "<img>" } else { "raster background" },
|
||||
number_to_string(op),
|
||||
if label.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(" \"{label}\"")
|
||||
}
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Line length too long ---
|
||||
if has_direct_text
|
||||
&& QUALITY_TEXT_TAGS.contains(&tag)
|
||||
&& rect.width > 0.0
|
||||
&& (text_len as f64) > line_max
|
||||
{
|
||||
let chars_per_line = rect.width / (font_size * 0.5);
|
||||
if chars_per_line > line_max + 5.0 {
|
||||
findings.push(RuleHit::new(
|
||||
"line-length",
|
||||
format!(
|
||||
"~{} chars/line (aim for <{})",
|
||||
number_to_string(math_round(chars_per_line)),
|
||||
number_to_string(line_max)
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Cramped padding ---
|
||||
let is_inline_code = tag == "code" && closest_or_none(dom, el, "pre").is_none();
|
||||
if !is_inline_code && has_direct_text && text_len > 20 && rect.width > 100.0 && rect.height > 30.0 {
|
||||
let borders = [
|
||||
spx("borderTopWidth"),
|
||||
spx("borderRightWidth"),
|
||||
spx("borderBottomWidth"),
|
||||
spx("borderLeftWidth"),
|
||||
];
|
||||
let border_count = borders.iter().filter(|w| **w > 0.0).count();
|
||||
let has_bg = has_visible_background_boundary(dom, el);
|
||||
if border_count >= 2 || has_bg {
|
||||
let mut v_pads: Vec<f64> = Vec::new();
|
||||
let mut h_pads: Vec<f64> = Vec::new();
|
||||
if has_bg || borders[0] > 0.0 {
|
||||
v_pads.push(spx("paddingTop"));
|
||||
}
|
||||
if has_bg || borders[2] > 0.0 {
|
||||
v_pads.push(spx("paddingBottom"));
|
||||
}
|
||||
if has_bg || borders[3] > 0.0 {
|
||||
h_pads.push(spx("paddingLeft"));
|
||||
}
|
||||
if has_bg || borders[1] > 0.0 {
|
||||
h_pads.push(spx("paddingRight"));
|
||||
}
|
||||
let v_min = v_pads.iter().copied().fold(f64::INFINITY, js::math_min);
|
||||
let h_min = h_pads.iter().copied().fold(f64::INFINITY, js::math_min);
|
||||
let v_thresh = js::math_max(4.0, font_size * 0.3);
|
||||
let h_thresh = js::math_max(8.0, font_size * 0.5);
|
||||
if v_min < v_thresh {
|
||||
findings.push(RuleHit::new(
|
||||
"cramped-padding",
|
||||
format!(
|
||||
"{}px vertical padding (need ≥{}px for {}px text)",
|
||||
number_to_string(v_min),
|
||||
to_fixed(v_thresh, 1),
|
||||
number_to_string(font_size)
|
||||
),
|
||||
));
|
||||
} else if h_min < h_thresh {
|
||||
findings.push(RuleHit::new(
|
||||
"cramped-padding",
|
||||
format!(
|
||||
"{}px horizontal padding (need ≥{}px for {}px text)",
|
||||
number_to_string(h_min),
|
||||
to_fixed(h_thresh, 1),
|
||||
number_to_string(font_size)
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Flush against a visible boundary ---
|
||||
{
|
||||
let upper_tag = js::to_upper_case(tag);
|
||||
let el_position = st("position");
|
||||
let children = dom.children(el);
|
||||
if !FLUSH_SKIP_TAGS.contains(&upper_tag.as_str())
|
||||
&& !has_direct_text
|
||||
&& el_position != "fixed"
|
||||
&& el_position != "absolute"
|
||||
&& !children.is_empty()
|
||||
{
|
||||
let border_w = [
|
||||
spx("borderTopWidth"),
|
||||
spx("borderRightWidth"),
|
||||
spx("borderBottomWidth"),
|
||||
spx("borderLeftWidth"),
|
||||
];
|
||||
let bc = |k: &str| css_color_is_transparent(Some(&st(k)));
|
||||
let border_visible = [
|
||||
border_w[0] > 0.0 && !bc("borderTopColor"),
|
||||
border_w[1] > 0.0 && !bc("borderRightColor"),
|
||||
border_w[2] > 0.0 && !bc("borderBottomColor"),
|
||||
border_w[3] > 0.0 && !bc("borderLeftColor"),
|
||||
];
|
||||
let mut outline_w = spx("outlineWidth");
|
||||
let mut outline_style_val = st("outlineStyle");
|
||||
let mut outline_color_val = st("outlineColor");
|
||||
let outline_short = st("outline");
|
||||
if outline_w == 0.0 && !outline_short.is_empty() {
|
||||
if let Some(m) = OUTLINE_W_RE.captures(&outline_short) {
|
||||
outline_w = pf0(m.get(1).map(|x| x.as_str()).unwrap_or(""));
|
||||
}
|
||||
if outline_style_val.is_empty() {
|
||||
outline_style_val = if OUTLINE_STYLE_RE.is_match(&outline_short) {
|
||||
"solid".to_string()
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
}
|
||||
if outline_color_val.is_empty() {
|
||||
if let Some(m) = OUTLINE_COLOR_RE.captures(&outline_short) {
|
||||
outline_color_val = m.get(1).map(|x| x.as_str()).unwrap_or("").to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
let outline_visible = outline_w > 0.0
|
||||
&& !css_color_is_transparent(Some(&outline_color_val))
|
||||
&& !outline_style_val.is_empty()
|
||||
&& outline_style_val != "none";
|
||||
let bg_visible = has_visible_background_boundary(dom, el);
|
||||
let any_visible = border_visible.iter().any(|b| *b) || outline_visible || bg_visible;
|
||||
if any_visible {
|
||||
let len = |e: ElId, k: &str| {
|
||||
resolve_length_px(Some(&dom.style(e, k)), font_size).unwrap_or(0.0)
|
||||
};
|
||||
let pad = [
|
||||
len(el, "paddingTop"),
|
||||
len(el, "paddingRight"),
|
||||
len(el, "paddingBottom"),
|
||||
len(el, "paddingLeft"),
|
||||
];
|
||||
const PAD_THRESHOLD: f64 = 2.0;
|
||||
const CHILD_INSULATE_THRESHOLD: f64 = 4.0;
|
||||
let mut children_insulate = [false; 4];
|
||||
for &child in &children {
|
||||
let child_pad = [
|
||||
len(child, "paddingTop"),
|
||||
len(child, "paddingRight"),
|
||||
len(child, "paddingBottom"),
|
||||
len(child, "paddingLeft"),
|
||||
];
|
||||
let child_margin = [
|
||||
len(child, "marginTop"),
|
||||
len(child, "marginRight"),
|
||||
len(child, "marginBottom"),
|
||||
len(child, "marginLeft"),
|
||||
];
|
||||
let cr = dom.rect(child);
|
||||
if cr.width > 0.0 && cr.height > 0.0 {
|
||||
if cr.top - rect.top >= CHILD_INSULATE_THRESHOLD {
|
||||
children_insulate[0] = true;
|
||||
}
|
||||
if rect.right - cr.right >= CHILD_INSULATE_THRESHOLD {
|
||||
children_insulate[1] = true;
|
||||
}
|
||||
if rect.bottom - cr.bottom >= CHILD_INSULATE_THRESHOLD {
|
||||
children_insulate[2] = true;
|
||||
}
|
||||
if cr.left - rect.left >= CHILD_INSULATE_THRESHOLD {
|
||||
children_insulate[3] = true;
|
||||
}
|
||||
}
|
||||
for s in 0..4 {
|
||||
if child_pad[s] >= CHILD_INSULATE_THRESHOLD
|
||||
|| child_margin[s] >= CHILD_INSULATE_THRESHOLD
|
||||
{
|
||||
children_insulate[s] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let text_flush = text_descendants_flush_sides(dom, el, rect);
|
||||
let full_bleed_bg_band = viewport_width > 0.0
|
||||
&& rect.width >= viewport_width * 0.94
|
||||
&& bg_visible
|
||||
&& !outline_visible;
|
||||
let side_names = ["top", "right", "bottom", "left"];
|
||||
let mut flush_sides: Vec<&str> = Vec::new();
|
||||
for s in 0..4 {
|
||||
let bg_bounds_side = bg_visible && !(full_bleed_bg_band && (s == 1 || s == 3));
|
||||
let side_bounded = border_visible[s] || outline_visible || bg_bounds_side;
|
||||
if side_bounded && pad[s] <= PAD_THRESHOLD && !children_insulate[s] && text_flush[s] {
|
||||
flush_sides.push(side_names[s]);
|
||||
}
|
||||
}
|
||||
|
||||
if !flush_sides.is_empty() {
|
||||
let mut has_text_child = false;
|
||||
for &child in &children {
|
||||
let child_text = js::trim(&dom.text_content(child)).to_string();
|
||||
if utf16_len(&child_text) > 4 {
|
||||
has_text_child = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if has_text_child {
|
||||
let cls_all = dom.class_name_prop(el).unwrap_or_default();
|
||||
let cls_all = js::trim(&cls_all).to_string();
|
||||
let cls = if cls_all.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
WS_RE.split(&cls_all).next().unwrap_or("").to_string()
|
||||
};
|
||||
let mut boundary_parts: Vec<String> = Vec::new();
|
||||
let border_sides_visible: Vec<&str> = (0..4)
|
||||
.filter(|i| border_visible[*i])
|
||||
.map(|i| side_names[i])
|
||||
.collect();
|
||||
if border_sides_visible.len() == 4 {
|
||||
boundary_parts.push("border".to_string());
|
||||
} else if !border_sides_visible.is_empty() {
|
||||
boundary_parts.push(format!("border-{}", border_sides_visible.join("/")));
|
||||
}
|
||||
if outline_visible {
|
||||
boundary_parts.push("outline".to_string());
|
||||
}
|
||||
if bg_visible {
|
||||
boundary_parts.push("bg".to_string());
|
||||
}
|
||||
let sides_label = if flush_sides.len() == 4 {
|
||||
"all sides".to_string()
|
||||
} else {
|
||||
flush_sides.join("/")
|
||||
};
|
||||
let tl = js::to_lower_case(tag);
|
||||
let ident = if !cls.is_empty() {
|
||||
format!("<{}> \"{}\"", tl, cls)
|
||||
} else {
|
||||
format!("<{}>", tl)
|
||||
};
|
||||
findings.push(RuleHit::new(
|
||||
"cramped-padding",
|
||||
format!(
|
||||
"{}: children flush against {} on {} (no inset)",
|
||||
ident,
|
||||
boundary_parts.join("+"),
|
||||
sides_label
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Body text touching viewport edge ---
|
||||
if has_direct_text
|
||||
&& text_len > 40
|
||||
&& matches!(js::to_upper_case(tag).as_str(), "P" | "LI")
|
||||
&& viewport_width > 0.0
|
||||
{
|
||||
let in_nav_header =
|
||||
closest_or_none(dom, el, "nav").is_some() || closest_or_none(dom, el, "header").is_some();
|
||||
let bg = st("backgroundColor");
|
||||
let has_own_bg = !bg.is_empty() && bg != "rgba(0, 0, 0, 0)" && bg != "transparent";
|
||||
let pos = st("position");
|
||||
let is_positioned = pos == "fixed" || pos == "absolute";
|
||||
let width_ratio = rect.width / viewport_width;
|
||||
let left_close = rect.left < 16.0;
|
||||
let right_close = rect.right > viewport_width - 16.0;
|
||||
if !in_nav_header && !has_own_bg && !is_positioned && width_ratio > 0.5 && (left_close || right_close) {
|
||||
let l = number_to_string(math_round(rect.left));
|
||||
let r = number_to_string(math_round(viewport_width - rect.right));
|
||||
let which = if left_close && right_close {
|
||||
format!("left {}px / right {}px", l, r)
|
||||
} else if left_close {
|
||||
format!("left {}px", l)
|
||||
} else {
|
||||
format!("right {}px", r)
|
||||
};
|
||||
findings.push(RuleHit::new(
|
||||
"body-text-viewport-edge",
|
||||
format!(
|
||||
"<{}> with {}-char body bleeds to viewport edge ({})",
|
||||
js::to_lower_case(tag),
|
||||
text_len,
|
||||
which
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let is_heading = matches!(tag, "h1" | "h2" | "h3" | "h4" | "h5" | "h6");
|
||||
|
||||
// --- Tight line height ---
|
||||
if has_direct_text && text_len > 50 && !is_heading {
|
||||
if let Some(lh) = q.line_height_px {
|
||||
if font_size > 0.0 {
|
||||
let ratio = lh / font_size;
|
||||
if ratio > 0.0 && ratio < 1.3 {
|
||||
findings.push(RuleHit::new(
|
||||
"tight-leading",
|
||||
format!("line-height {}x (need >=1.3)", to_fixed(ratio, 2)),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Justified text (without hyphens) ---
|
||||
if has_direct_text && st("textAlign") == "justify" {
|
||||
let hyphens = {
|
||||
let a = st("hyphens");
|
||||
if !a.is_empty() {
|
||||
a
|
||||
} else {
|
||||
st("webkitHyphens")
|
||||
}
|
||||
};
|
||||
if hyphens != "auto" {
|
||||
findings.push(RuleHit::new(
|
||||
"justified-text",
|
||||
"text-align: justify without hyphens: auto".to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Tiny body text ---
|
||||
if has_direct_text && text_len > 20 && font_size < 12.0 {
|
||||
let skip_tags = ["sub", "sup", "code", "kbd", "samp", "var", "caption", "figcaption"];
|
||||
let in_ui_context = closest_or_none(dom, el, TINY_TEXT_UI_CONTEXT).is_some();
|
||||
let is_uppercase = st("textTransform") == "uppercase";
|
||||
if !skip_tags.contains(&tag)
|
||||
&& !in_ui_context
|
||||
&& !is_uppercase
|
||||
&& !is_non_rendered_text(dom, el, tag)
|
||||
{
|
||||
findings.push(RuleHit::new(
|
||||
"tiny-text",
|
||||
format!("{}px body text", number_to_string(font_size)),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Undersized functional / UI text ---
|
||||
{
|
||||
let dt = js::trim(&collapse_ws(&direct_text(dom, el))).to_string();
|
||||
let dt_len = utf16_len(&dt);
|
||||
let ui_skip_tags = ["sub", "sup", "option"];
|
||||
if font_size > 0.0
|
||||
&& font_size < 11.0
|
||||
&& dt_len >= 2
|
||||
&& !ui_skip_tags.contains(&tag)
|
||||
&& !is_non_rendered_text(dom, el, tag)
|
||||
{
|
||||
let is_exempt_context = matches_or_closest(dom, el, EXEMPT_CONTEXT);
|
||||
if !is_exempt_context && !is_visually_hidden(dom, el) {
|
||||
let is_interactive = matches_or_closest(dom, el, INTERACTIVE);
|
||||
let is_furniture = matches_or_closest(dom, el, FURNITURE);
|
||||
let is_smallprint = matches_or_closest(dom, el, SMALLPRINT);
|
||||
let floor = if !is_interactive && is_smallprint { 10.0 } else { 11.0 };
|
||||
if font_size < floor && (is_interactive || is_furniture || dt_len <= 20) {
|
||||
let excerpt = slice_utf16_prefix(&dt, 40);
|
||||
findings.push(RuleHit::new(
|
||||
"undersized-ui-text",
|
||||
format!(
|
||||
"{}px functional text \"{}\" (below {}px floor)",
|
||||
number_to_string(font_size),
|
||||
excerpt,
|
||||
number_to_string(floor)
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- All-caps body text ---
|
||||
if has_direct_text && text_len > 30 && st("textTransform") == "uppercase" && !is_heading {
|
||||
findings.push(RuleHit::new(
|
||||
"all-caps-body",
|
||||
format!("text-transform: uppercase on {} chars of body text", text_len),
|
||||
));
|
||||
}
|
||||
|
||||
// --- Wide letter spacing on body text ---
|
||||
if has_direct_text && text_len > 20 && st("textTransform") != "uppercase" {
|
||||
if let Some(ls) = q.letter_spacing_px {
|
||||
if ls > 0.0 && font_size > 0.0 {
|
||||
let tracking_em = ls / font_size;
|
||||
if tracking_em > 0.05 {
|
||||
findings.push(RuleHit::new(
|
||||
"wide-tracking",
|
||||
format!("letter-spacing: {}em on body text", to_fixed(tracking_em, 2)),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Crushed letter spacing ---
|
||||
if has_direct_text && text_len > 20 && font_size > 0.0 {
|
||||
if let Some(ls) = q.letter_spacing_px {
|
||||
if ls < 0.0 {
|
||||
let tracking_em = ls / font_size;
|
||||
if tracking_em <= -0.05 {
|
||||
let excerpt = slice_utf16_prefix(
|
||||
&collapse_ws(js::trim(&dom.text_content(el))),
|
||||
40,
|
||||
);
|
||||
findings.push(RuleHit::new(
|
||||
"extreme-negative-tracking",
|
||||
format!("letter-spacing: {}em — \"{}\"", to_fixed(tracking_em, 2), excerpt),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
findings
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#checkElementQualityDOM(el)
|
||||
pub fn check_element_quality_dom(dom: &dyn Dom, el: ElId, config: &BrowserConfig) -> Vec<RuleHit> {
|
||||
let tag = tag_lower(dom, el);
|
||||
let has_direct_text = has_direct_text_longer_than(dom, el, 10);
|
||||
let text_len = utf16_len(js::trim(&dom.text_content(el)));
|
||||
let font_size = {
|
||||
let n = parse_float(&dom.style(el, "fontSize"));
|
||||
if crate::js_ext_a::num_truthy(n) {
|
||||
n
|
||||
} else {
|
||||
16.0
|
||||
}
|
||||
};
|
||||
let line_height_px = resolve_length_px(Some(&dom.style(el, "lineHeight")), font_size);
|
||||
let letter_spacing_px = resolve_length_px(Some(&dom.style(el, "letterSpacing")), font_size);
|
||||
let rect = dom.rect(el);
|
||||
let line_max = config.line_max();
|
||||
let viewport_width = {
|
||||
let w = dom.inner_width();
|
||||
if crate::js_ext_a::num_truthy(w) {
|
||||
w
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
};
|
||||
check_quality(
|
||||
dom,
|
||||
&QualityInput {
|
||||
el,
|
||||
tag,
|
||||
has_direct_text,
|
||||
text_len,
|
||||
font_size,
|
||||
line_height_px,
|
||||
letter_spacing_px,
|
||||
rect,
|
||||
line_max,
|
||||
viewport_width,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#checkPageQualityFromDoc(doc)
|
||||
pub fn check_page_quality_from_doc(dom: &dyn Dom) -> Vec<RuleHit> {
|
||||
let mut findings = Vec::new();
|
||||
let mut prev_level: i64 = 0;
|
||||
let mut prev_text = String::new();
|
||||
for h in dom.query_all(None, "h1, h2, h3, h4, h5, h6").unwrap_or_default() {
|
||||
let tag = dom.tag_name(h);
|
||||
// JS `parseInt(h.tagName[1])`
|
||||
let level = js::parse_int(&tag.chars().nth(1).map(|c| c.to_string()).unwrap_or_default(), 10);
|
||||
let level = if level.is_nan() { 0 } else { level as i64 };
|
||||
let text = slice_utf16_prefix(&collapse_ws(js::trim(&dom.text_content(h))), 60);
|
||||
if prev_level > 0 && level > prev_level + 1 {
|
||||
findings.push(RuleHit::new(
|
||||
"skipped-heading",
|
||||
format!(
|
||||
"<h{}> \"{}\" followed by <h{}> \"{}\" (missing h{})",
|
||||
prev_level,
|
||||
prev_text,
|
||||
level,
|
||||
text,
|
||||
prev_level + 1
|
||||
),
|
||||
));
|
||||
}
|
||||
prev_level = level;
|
||||
prev_text = text;
|
||||
}
|
||||
findings
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#checkPageQualityDOM() — `{ type, detail }` shape.
|
||||
pub fn check_page_quality_dom(dom: &dyn Dom) -> Vec<BrowserFinding> {
|
||||
check_page_quality_from_doc(dom)
|
||||
.iter()
|
||||
.map(BrowserFinding::from_hit)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::browser::fake_dom::FakeDom;
|
||||
|
||||
fn text_el(d: &mut FakeDom, body: ElId, tag: &str, text: &str, font: &str) -> ElId {
|
||||
let p = d.add(Some(body), tag);
|
||||
d.add_text(p, text);
|
||||
d.set_styles(
|
||||
p,
|
||||
&[
|
||||
("fontSize", font),
|
||||
("lineHeight", "normal"),
|
||||
("letterSpacing", "normal"),
|
||||
("backgroundColor", "rgba(0, 0, 0, 0)"),
|
||||
("position", "static"),
|
||||
("textTransform", "none"),
|
||||
("textAlign", "start"),
|
||||
],
|
||||
);
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_length_and_viewport_edge() {
|
||||
let mut d = FakeDom::new();
|
||||
let (_h, body) = d.with_page();
|
||||
let long = "x".repeat(120);
|
||||
let p = text_el(&mut d, body, "p", &long, "16px");
|
||||
d.set_rect(p, 0.0, 100.0, 1200.0, 40.0);
|
||||
let hits = check_element_quality_dom(&d, p, &BrowserConfig::default());
|
||||
let ids: Vec<&str> = hits.iter().map(|h| h.id.as_str()).collect();
|
||||
assert!(ids.contains(&"line-length"), "{ids:?}");
|
||||
assert_eq!(hits[0].snippet, "~150 chars/line (aim for <80)");
|
||||
assert!(ids.contains(&"body-text-viewport-edge"));
|
||||
let edge = hits.iter().find(|h| h.id == "body-text-viewport-edge").unwrap();
|
||||
assert_eq!(edge.snippet, "<p> with 120-char body bleeds to viewport edge (left 0px)");
|
||||
// narrower, inset paragraph: neither fires
|
||||
d.set_rect(p, 40.0, 100.0, 600.0, 40.0);
|
||||
let hits = check_element_quality_dom(&d, p, &BrowserConfig::default());
|
||||
assert!(hits.is_empty(), "{hits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cramped_padding_vertical() {
|
||||
let mut d = FakeDom::new();
|
||||
let (_h, body) = d.with_page();
|
||||
d.set_style(body, "backgroundColor", "rgb(255, 255, 255)");
|
||||
let p = text_el(&mut d, body, "div", &"word ".repeat(10), "16px");
|
||||
d.set_rect(p, 40.0, 100.0, 300.0, 60.0);
|
||||
d.set_styles(
|
||||
p,
|
||||
&[
|
||||
("backgroundColor", "rgb(240, 240, 240)"),
|
||||
("borderTopWidth", "0px"),
|
||||
("borderRightWidth", "0px"),
|
||||
("borderBottomWidth", "0px"),
|
||||
("borderLeftWidth", "0px"),
|
||||
("paddingTop", "2px"),
|
||||
("paddingBottom", "12px"),
|
||||
("paddingLeft", "12px"),
|
||||
("paddingRight", "12px"),
|
||||
],
|
||||
);
|
||||
let hits = check_element_quality_dom(&d, p, &BrowserConfig::default());
|
||||
assert_eq!(hits.len(), 1, "{hits:?}");
|
||||
assert_eq!(hits[0].snippet, "2px vertical padding (need ≥4.8px for 16px text)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flush_children_against_border() {
|
||||
let mut d = FakeDom::new();
|
||||
let (_h, body) = d.with_page();
|
||||
let card = d.add(Some(body), "section");
|
||||
d.set_attr(card, "class", "card-frame extra");
|
||||
d.set_rect(card, 0.0, 0.0, 400.0, 200.0);
|
||||
d.set_styles(
|
||||
card,
|
||||
&[
|
||||
("position", "static"),
|
||||
("borderTopWidth", "1px"),
|
||||
("borderRightWidth", "1px"),
|
||||
("borderBottomWidth", "1px"),
|
||||
("borderLeftWidth", "1px"),
|
||||
("borderTopColor", "rgb(0, 0, 0)"),
|
||||
("borderRightColor", "rgb(0, 0, 0)"),
|
||||
("borderBottomColor", "rgb(0, 0, 0)"),
|
||||
("borderLeftColor", "rgb(0, 0, 0)"),
|
||||
("outlineWidth", "0px"),
|
||||
("backgroundColor", "rgba(0, 0, 0, 0)"),
|
||||
("paddingTop", "28px"),
|
||||
("paddingRight", "0px"),
|
||||
("paddingBottom", "0px"),
|
||||
("paddingLeft", "0px"),
|
||||
("fontSize", "16px"),
|
||||
],
|
||||
);
|
||||
let p = text_el(&mut d, card, "p", "Hello there friend", "16px");
|
||||
d.set_rect(p, 0.0, 28.0, 400.0, 20.0);
|
||||
d.set_styles(p, &[("paddingTop", "0px"), ("paddingRight", "0px"), ("paddingBottom", "0px"), ("paddingLeft", "0px"), ("marginTop", "0px"), ("marginRight", "0px"), ("marginBottom", "0px"), ("marginLeft", "0px")]);
|
||||
let hits = check_element_quality_dom(&d, card, &BrowserConfig::default());
|
||||
assert_eq!(hits.len(), 1, "{hits:?}");
|
||||
assert_eq!(
|
||||
hits[0].snippet,
|
||||
"<section> \"card-frame\": children flush against border on right/left (no inset)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typography_rules() {
|
||||
let mut d = FakeDom::new();
|
||||
let (_h, body) = d.with_page();
|
||||
let text = "a".repeat(60);
|
||||
let p = text_el(&mut d, body, "p", &text, "16px");
|
||||
d.set_rect(p, 40.0, 100.0, 300.0, 40.0);
|
||||
d.set_styles(p, &[("lineHeight", "16px"), ("textAlign", "justify"), ("hyphens", "manual"), ("letterSpacing", "2px")]);
|
||||
let hits = check_element_quality_dom(&d, p, &BrowserConfig::default());
|
||||
let ids: Vec<&str> = hits.iter().map(|h| h.id.as_str()).collect();
|
||||
assert_eq!(ids, vec!["tight-leading", "justified-text", "wide-tracking"], "{hits:?}");
|
||||
assert_eq!(hits[0].snippet, "line-height 1.00x (need >=1.3)");
|
||||
assert_eq!(hits[2].snippet, "letter-spacing: 0.13em on body text");
|
||||
d.set_styles(p, &[("lineHeight", "24px"), ("textAlign", "left"), ("letterSpacing", "-1px"), ("textTransform", "uppercase")]);
|
||||
let hits = check_element_quality_dom(&d, p, &BrowserConfig::default());
|
||||
let ids: Vec<&str> = hits.iter().map(|h| h.id.as_str()).collect();
|
||||
assert_eq!(ids, vec!["all-caps-body", "extreme-negative-tracking"], "{hits:?}");
|
||||
assert_eq!(hits[1].snippet, format!("letter-spacing: -0.06em — \"{}\"", "a".repeat(40)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiny_and_undersized_text() {
|
||||
let mut d = FakeDom::new();
|
||||
let (_h, body) = d.with_page();
|
||||
let p = text_el(&mut d, body, "p", "This is small body copy text", "10px");
|
||||
d.set_rect(p, 40.0, 100.0, 300.0, 40.0);
|
||||
let hits = check_element_quality_dom(&d, p, &BrowserConfig::default());
|
||||
let ids: Vec<&str> = hits.iter().map(|h| h.id.as_str()).collect();
|
||||
assert_eq!(ids, vec!["tiny-text"], "{hits:?}");
|
||||
assert_eq!(hits[0].snippet, "10px body text");
|
||||
// short functional label under 11px
|
||||
let s = text_el(&mut d, body, "span", "Meta 12:00", "9px");
|
||||
d.set_rect(s, 40.0, 100.0, 60.0, 12.0);
|
||||
let hits = check_element_quality_dom(&d, s, &BrowserConfig::default());
|
||||
assert_eq!(hits.len(), 1, "{hits:?}");
|
||||
assert_eq!(hits[0].snippet, "9px functional text \"Meta 12:00\" (below 11px floor)");
|
||||
// smallprint context softens the floor to 10px
|
||||
d.add_selector(s, SMALLPRINT);
|
||||
d.set_style(s, "fontSize", "10px");
|
||||
assert!(check_element_quality_dom(&d, s, &BrowserConfig::default()).is_empty());
|
||||
// sr-only exempts
|
||||
d.set_style(s, "fontSize", "9px");
|
||||
d.add_selector(s, SR_ONLY_SELECTOR);
|
||||
assert!(check_element_quality_dom(&d, s, &BrowserConfig::default()).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skipped_heading() {
|
||||
let mut d = FakeDom::new();
|
||||
let (_h, body) = d.with_page();
|
||||
let h1 = d.add(Some(body), "h1");
|
||||
d.add_text(h1, " Title here ");
|
||||
let h3 = d.add(Some(body), "h3");
|
||||
d.add_text(h3, "Sub");
|
||||
let f = check_page_quality_dom(&d);
|
||||
assert_eq!(f.len(), 1);
|
||||
assert_eq!(f[0].type_, "skipped-heading");
|
||||
assert_eq!(f[0].detail, "<h1> \"Title here\" followed by <h3> \"Sub\" (missing h2)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visually_hidden_and_non_rendered() {
|
||||
let mut d = FakeDom::new();
|
||||
let (_h, body) = d.with_page();
|
||||
let s = d.add(Some(body), "span");
|
||||
d.set_styles(s, &[("position", "absolute"), ("clip", "rect(0px, 0px, 0px, 0px)")]);
|
||||
assert!(is_visually_hidden(&d, s));
|
||||
d.set_styles(s, &[("clip", "auto"), ("width", "1px"), ("height", "20px"), ("overflow", "hidden")]);
|
||||
assert!(is_visually_hidden(&d, s));
|
||||
d.set_style(s, "overflow", "visible");
|
||||
assert!(!is_visually_hidden(&d, s));
|
||||
assert!(is_non_rendered_text(&d, s, "script"));
|
||||
d.set_style(s, "visibility", "collapse");
|
||||
assert!(is_non_rendered_text(&d, s, "span"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
//! The snapshot DOM and its one-shot findings run. Everything except the
|
||||
//! run itself lives in `impeccable_foundation::browser::snapshot`; this
|
||||
//! module re-exports it under the path callers already use and adds
|
||||
//! [`collect_findings_from_snapshot`], which drives the browser driver.
|
||||
|
||||
pub use impeccable_foundation::browser::snapshot::*;
|
||||
|
||||
/// A one-shot findings run over a snapshot: parse, collect, serialize.
|
||||
/// `Err(needs)` when the run asked for hit tests the snapshot lacked; supply
|
||||
/// them (`hits` in the snapshot or [`SnapshotDom::add_facts`]) and run again.
|
||||
pub fn collect_findings_from_snapshot(
|
||||
dom: &SnapshotDom,
|
||||
config: &super::BrowserConfig,
|
||||
) -> Result<super::driver::CollectResult, Needs> {
|
||||
dom.reset_memo();
|
||||
let out = super::driver::collect_browser_findings(dom, config);
|
||||
if dom.has_needs() {
|
||||
return Err(dom.take_needs());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -0,0 +1,560 @@
|
||||
//! Kicker / numbered-label / em-dash / repeated-text browser collectors from
|
||||
//! `checks.mjs` (`collectKickerCandidates`, `checkKickerAboveHeadingDOM`,
|
||||
//! `collectNumberedSectionLabelCandidates`, `checkNumberedSectionLabelsDOM`,
|
||||
//! `checkEmDashOveruseDOM`, `collectRepeatedContainerTextFindings`,
|
||||
//! `checkRepeatedContainerTextDOM`) against the [`Dom`] probe. The pure
|
||||
//! gates live in `checks::rules` / `checks::text_rules`.
|
||||
|
||||
use super::dom::{tag_lower, Dom, ElId, ElStyle};
|
||||
use super::element_checks::{class_selector, is_rendered_for_browser_rule};
|
||||
use crate::checks::measures::resolve_length_px;
|
||||
use crate::checks::rules::{check_kicker_above_heading, KickerCandidate, RuleHit};
|
||||
use crate::checks::text_rules::{
|
||||
check_em_dash_overuse, check_numbered_section_labels, is_kicker_candidate,
|
||||
is_numbered_section_label_candidate, is_repeated_text_container, parse_numbered_label_text,
|
||||
strip_edge_quotes, HEADING_TAGS, KICKER_CARD_CONTEXT_SELECTOR, KICKER_SKIP_SELECTOR,
|
||||
KickerCandidateInput, NumberedLabelCandidate, NumberedLabelCandidateInput,
|
||||
REPEATED_TEXT_CONTAINER_TAGS, REPEATED_TEXT_SKIP_SELECTOR,
|
||||
};
|
||||
use crate::js::{self, parse_float, parse_int};
|
||||
use crate::js_ext_a::num_truthy;
|
||||
use crate::js_ext_b::{slice_utf16_prefix, utf16_len};
|
||||
use once_cell::sync::Lazy;
|
||||
use regex::Regex;
|
||||
|
||||
static WS_RE: Lazy<Regex> = Lazy::new(|| Regex::new(&format!("{}+", js::WS)).expect("WS_RE"));
|
||||
|
||||
/// JS `s.replace(/\s+/g, ' ')`.
|
||||
fn collapse_ws(s: &str) -> String {
|
||||
WS_RE.replace_all(s, " ").into_owned()
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#cleanInlineText(el): direct text nodes joined with a
|
||||
/// space, whitespace collapsed, trimmed.
|
||||
pub fn clean_inline_text(dom: &dyn Dom, el: ElId) -> String {
|
||||
let joined = dom.direct_text_nodes(el).join(" ");
|
||||
js::trim(&collapse_ws(&joined)).to_string()
|
||||
}
|
||||
|
||||
/// `(el.textContent || '').replace(/\s+/g, ' ').trim()`
|
||||
fn collapsed_text_content(dom: &dyn Dom, el: ElId) -> String {
|
||||
js::trim(&collapse_ws(&dom.text_content(el))).to_string()
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#isKickerCardContext(heading, kicker)
|
||||
pub fn is_kicker_card_context(dom: &dyn Dom, heading: ElId, kicker: ElId) -> bool {
|
||||
match dom.closest(heading, KICKER_CARD_CONTEXT_SELECTOR) {
|
||||
Ok(Some(item)) => dom.contains(item, kicker),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
static HEADING_LEVEL_RE: Lazy<Regex> =
|
||||
Lazy::new(|| Regex::new(r"^h([1-6])$").expect("HEADING_LEVEL_RE"));
|
||||
|
||||
/// JS: checks.mjs#kickerHeadingLevel(heading)
|
||||
pub fn kicker_heading_level(dom: &dyn Dom, heading: ElId) -> f64 {
|
||||
let tag = tag_lower(dom, heading);
|
||||
if let Some(m) = HEADING_LEVEL_RE.captures(&tag) {
|
||||
return parse_int(&m[1], 10);
|
||||
}
|
||||
let role = dom.attr(heading, "role").unwrap_or_default();
|
||||
if js::to_lower_case(&role) != "heading" {
|
||||
return 0.0;
|
||||
}
|
||||
let aria_level = parse_int(&dom.attr(heading, "aria-level").unwrap_or_default(), 10);
|
||||
if aria_level.is_finite() && aria_level >= 1.0 {
|
||||
aria_level
|
||||
} else {
|
||||
2.0
|
||||
}
|
||||
}
|
||||
|
||||
/// `(value, fontSize) => resolveLengthPx(value, fontSize) || 0`
|
||||
fn resolve_len_or_zero(value: &str, font_size: f64) -> f64 {
|
||||
match resolve_length_px(Some(value), font_size) {
|
||||
Some(n) if num_truthy(n) => n,
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// `resolveLetterSpacing(style.fontSize || '', 16) || parseFloat(style.fontSize) || 0`
|
||||
fn font_size_of(dom: &dyn Dom, el: ElId) -> f64 {
|
||||
let raw = dom.style(el, "fontSize");
|
||||
let a = resolve_len_or_zero(&raw, 16.0);
|
||||
if num_truthy(a) {
|
||||
return a;
|
||||
}
|
||||
let n = parse_float(&raw);
|
||||
if num_truthy(n) {
|
||||
n
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
|
||||
fn strip_edge_quotes_slice(text: &str, n: usize) -> String {
|
||||
slice_utf16_prefix(&strip_edge_quotes(text), n)
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#collectKickerCandidates(document, getComputedStyle, resolveLengthPx || 0)
|
||||
pub fn collect_kicker_candidates(dom: &dyn Dom) -> Vec<KickerCandidate> {
|
||||
let mut candidates = Vec::new();
|
||||
for heading in dom
|
||||
.query_all(None, "h1, h2, h3, h4, [role=\"heading\"]")
|
||||
.unwrap_or_default()
|
||||
{
|
||||
let heading_level = kicker_heading_level(dom, heading);
|
||||
if !num_truthy(heading_level) || heading_level > 4.0 {
|
||||
continue;
|
||||
}
|
||||
if super::dom::closest_or_none(dom, heading, KICKER_SKIP_SELECTOR).is_some() {
|
||||
continue;
|
||||
}
|
||||
if super::dom::closest_or_none(
|
||||
dom,
|
||||
heading,
|
||||
"[role=\"tabpanel\"], [role=\"dialog\"], [role=\"application\"], dialog",
|
||||
)
|
||||
.is_some()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Some(kicker) = dom.previous_element_sibling(heading) else {
|
||||
continue;
|
||||
};
|
||||
if super::dom::closest_or_none(dom, kicker, KICKER_SKIP_SELECTOR).is_some() {
|
||||
continue;
|
||||
}
|
||||
if is_kicker_card_context(dom, heading, kicker) {
|
||||
continue;
|
||||
}
|
||||
let heading_tag = tag_lower(dom, heading);
|
||||
let heading_text = collapsed_text_content(dom, heading);
|
||||
let kicker_text = {
|
||||
let t = clean_inline_text(dom, kicker);
|
||||
if t.is_empty() {
|
||||
collapsed_text_content(dom, kicker)
|
||||
} else {
|
||||
t
|
||||
}
|
||||
};
|
||||
let heading_font_size = font_size_of(dom, heading);
|
||||
let kicker_font_size = font_size_of(dom, kicker);
|
||||
let kicker_letter_spacing =
|
||||
resolve_len_or_zero(&dom.style(kicker, "letterSpacing"), kicker_font_size);
|
||||
let kicker_font_variant = format!(
|
||||
"{} {}",
|
||||
dom.style(kicker, "fontVariant"),
|
||||
dom.style(kicker, "fontVariantCaps")
|
||||
);
|
||||
if !is_kicker_candidate(&KickerCandidateInput {
|
||||
heading_level,
|
||||
heading_text: &heading_text,
|
||||
heading_font_size,
|
||||
kicker_tag: &tag_lower(dom, kicker),
|
||||
kicker_text: &kicker_text,
|
||||
kicker_text_transform: &dom.style(kicker, "textTransform"),
|
||||
kicker_font_variant: &kicker_font_variant,
|
||||
kicker_font_size,
|
||||
kicker_letter_spacing,
|
||||
}) {
|
||||
continue;
|
||||
}
|
||||
if heading_tag == "h1" && heading_font_size >= 48.0 && kicker_letter_spacing >= 1.6 {
|
||||
continue;
|
||||
}
|
||||
candidates.push(KickerCandidate {
|
||||
heading_tag,
|
||||
heading_text: strip_edge_quotes_slice(&heading_text, 60),
|
||||
kicker_text: slice_utf16_prefix(&kicker_text, 40),
|
||||
});
|
||||
}
|
||||
candidates
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#checkKickerAboveHeadingDOM()
|
||||
pub fn check_kicker_above_heading_dom(dom: &dyn Dom) -> Vec<RuleHit> {
|
||||
check_kicker_above_heading(&collect_kicker_candidates(dom))
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#collectNumberedSectionLabelCandidates(document, ...)
|
||||
pub fn collect_numbered_section_label_candidates(dom: &dyn Dom) -> Vec<NumberedLabelCandidate> {
|
||||
let mut candidates = Vec::new();
|
||||
let mut seen_labels: Vec<ElId> = Vec::new();
|
||||
for heading in dom.query_all(None, "h2, h3, h4").unwrap_or_default() {
|
||||
if super::dom::closest_or_none(dom, heading, KICKER_SKIP_SELECTOR).is_some() {
|
||||
continue;
|
||||
}
|
||||
let mut label = dom.previous_element_sibling(heading);
|
||||
if label.is_none() {
|
||||
if let Some(parent) = dom.parent(heading) {
|
||||
let first_child = dom.children(parent).into_iter().next();
|
||||
if first_child == Some(heading) {
|
||||
label = dom.previous_element_sibling(parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(label) = label else {
|
||||
continue;
|
||||
};
|
||||
if seen_labels.contains(&label) {
|
||||
continue;
|
||||
}
|
||||
if super::dom::closest_or_none(dom, label, KICKER_SKIP_SELECTOR).is_some() {
|
||||
continue;
|
||||
}
|
||||
if HEADING_TAGS.contains(&tag_lower(dom, label).as_str()) {
|
||||
continue;
|
||||
}
|
||||
if is_kicker_card_context(dom, heading, label) {
|
||||
continue;
|
||||
}
|
||||
let label_text = {
|
||||
let t = clean_inline_text(dom, label);
|
||||
if t.is_empty() {
|
||||
collapsed_text_content(dom, label)
|
||||
} else {
|
||||
t
|
||||
}
|
||||
};
|
||||
let Some(parsed) = parse_numbered_label_text(Some(&label_text)) else {
|
||||
continue;
|
||||
};
|
||||
let heading_text = collapsed_text_content(dom, heading);
|
||||
let heading_font_size = font_size_of(dom, heading);
|
||||
let label_font_size = font_size_of(dom, label);
|
||||
if !is_numbered_section_label_candidate(&NumberedLabelCandidateInput {
|
||||
heading_tag: &tag_lower(dom, heading),
|
||||
heading_text: &heading_text,
|
||||
heading_font_size,
|
||||
label_tag: &tag_lower(dom, label),
|
||||
label_index: Some(parsed.index),
|
||||
label_text: &parsed.text,
|
||||
label_font_size,
|
||||
label_letter_spacing: resolve_len_or_zero(
|
||||
&dom.style(label, "letterSpacing"),
|
||||
label_font_size,
|
||||
),
|
||||
label_font_weight: &dom.style(label, "fontWeight"),
|
||||
label_font_family: &dom.style(label, "fontFamily"),
|
||||
label_text_transform: &dom.style(label, "textTransform"),
|
||||
label_color: &dom.style(label, "color"),
|
||||
}) {
|
||||
continue;
|
||||
}
|
||||
seen_labels.push(label);
|
||||
candidates.push(NumberedLabelCandidate {
|
||||
index: parsed.index,
|
||||
label_text: slice_utf16_prefix(&parsed.text, 24),
|
||||
heading_tag: tag_lower(dom, heading),
|
||||
heading_text: strip_edge_quotes_slice(&heading_text, 60),
|
||||
});
|
||||
}
|
||||
candidates
|
||||
}
|
||||
|
||||
fn hits(v: Vec<crate::checks::measures::Finding>) -> Vec<RuleHit> {
|
||||
v.into_iter()
|
||||
.map(|f| RuleHit {
|
||||
id: f.id,
|
||||
snippet: f.snippet,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#checkNumberedSectionLabelsDOM()
|
||||
pub fn check_numbered_section_labels_dom(dom: &dyn Dom) -> Vec<RuleHit> {
|
||||
hits(check_numbered_section_labels(
|
||||
&collect_numbered_section_label_candidates(dom),
|
||||
None,
|
||||
))
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#checkEmDashOveruseDOM()
|
||||
pub fn check_em_dash_overuse_dom(dom: &dyn Dom) -> Vec<RuleHit> {
|
||||
let Some(body) = dom.body() else {
|
||||
return Vec::new();
|
||||
};
|
||||
// innerText when it is a non-empty string, else textContent.
|
||||
let text = match dom.inner_text(body) {
|
||||
Some(t) => t,
|
||||
None => dom.text_content(body),
|
||||
};
|
||||
hits(check_em_dash_overuse(Some(&text)))
|
||||
}
|
||||
|
||||
static ICON_CLASS_RE: Lazy<Regex> = Lazy::new(|| {
|
||||
// JS `/icon|material-symbols|(?:^|\s)fa[srlbd]?(?:\s|-|$)/i`, ASCII folding.
|
||||
Regex::new(&format!(
|
||||
"{icon}|{ms}|(?:^|{ws}){fa}[srlbdSRLBD]?(?:{ws}|-|$)",
|
||||
icon = js::ci("icon"),
|
||||
ms = js::ci("material-symbols"),
|
||||
fa = js::ci("fa"),
|
||||
ws = js::WS
|
||||
))
|
||||
.expect("ICON_CLASS_RE")
|
||||
});
|
||||
static ALPHA_RE: Lazy<Regex> = Lazy::new(|| Regex::new("[a-zA-Z]").expect("ALPHA_RE"));
|
||||
|
||||
/// JS: checks.mjs#collectRepeatedContainerTextFindings(doc, getStyle, opts)
|
||||
/// with `isVisible` supplied by the caller.
|
||||
pub fn collect_repeated_container_text_findings(
|
||||
dom: &dyn Dom,
|
||||
is_visible: &dyn Fn(ElId) -> bool,
|
||||
) -> Vec<RuleHit> {
|
||||
let mut findings = Vec::new();
|
||||
let mut containers: Vec<ElId> = Vec::new();
|
||||
for el in dom.query_all(None, "*").unwrap_or_default() {
|
||||
if !REPEATED_TEXT_CONTAINER_TAGS.contains(&tag_lower(dom, el).as_str()) {
|
||||
continue;
|
||||
}
|
||||
if super::dom::closest_or_none(dom, el, REPEATED_TEXT_SKIP_SELECTOR).is_some() {
|
||||
continue;
|
||||
}
|
||||
let style = ElStyle { dom, el };
|
||||
if !is_repeated_text_container(Some(&style)) {
|
||||
continue;
|
||||
}
|
||||
containers.push(el);
|
||||
}
|
||||
|
||||
for &container in &containers {
|
||||
if !is_visible(container) {
|
||||
continue;
|
||||
}
|
||||
let descendants = dom.query_all(Some(container), "*").unwrap_or_default();
|
||||
if descendants.len() > 250 {
|
||||
continue;
|
||||
}
|
||||
// text -> signatures, in first-seen order (JS Map).
|
||||
let mut groups: Vec<(String, Vec<String>)> = Vec::new();
|
||||
for &d in &descendants {
|
||||
let mut anc = dom.parent(d);
|
||||
let mut owned_by_inner = false;
|
||||
while let Some(a) = anc {
|
||||
if a == container {
|
||||
break;
|
||||
}
|
||||
if containers.contains(&a) {
|
||||
owned_by_inner = true;
|
||||
break;
|
||||
}
|
||||
anc = dom.parent(a);
|
||||
}
|
||||
if owned_by_inner {
|
||||
continue;
|
||||
}
|
||||
if super::dom::closest_or_none(dom, d, REPEATED_TEXT_SKIP_SELECTOR).is_some() {
|
||||
continue;
|
||||
}
|
||||
if ICON_CLASS_RE.is_match(&dom.attr(d, "class").unwrap_or_default()) {
|
||||
continue;
|
||||
}
|
||||
if !is_visible(d) {
|
||||
continue;
|
||||
}
|
||||
let direct = clean_inline_text(dom, d);
|
||||
let len = utf16_len(&direct);
|
||||
if !(4..=48).contains(&len) {
|
||||
continue;
|
||||
}
|
||||
if !ALPHA_RE.is_match(&direct) {
|
||||
continue;
|
||||
}
|
||||
let mut sig: Vec<String> = Vec::new();
|
||||
let mut cur = Some(d);
|
||||
while let Some(c) = cur {
|
||||
if c == container {
|
||||
break;
|
||||
}
|
||||
let raw = dom.attr(c, "class").unwrap_or_default();
|
||||
let raw_cls = js::trim(&raw);
|
||||
let mut cls: Vec<&str> = if raw_cls.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
WS_RE.split(raw_cls).filter(|s| !s.is_empty()).collect()
|
||||
};
|
||||
cls.sort_by(|a, b| a.encode_utf16().cmp(b.encode_utf16()));
|
||||
let cls = cls.join(".");
|
||||
sig.push(if cls.is_empty() {
|
||||
tag_lower(dom, c)
|
||||
} else {
|
||||
format!("{}.{}", tag_lower(dom, c), cls)
|
||||
});
|
||||
cur = dom.parent(c);
|
||||
}
|
||||
let joined = sig.join(">");
|
||||
match groups.iter_mut().find(|(t, _)| *t == direct) {
|
||||
Some((_, sigs)) => sigs.push(joined),
|
||||
None => groups.push((direct, vec![joined])),
|
||||
}
|
||||
}
|
||||
for (text, sigs) in &groups {
|
||||
if sigs.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
let mut distinct: Vec<&String> = Vec::new();
|
||||
for s in sigs {
|
||||
if !distinct.contains(&s) {
|
||||
distinct.push(s);
|
||||
}
|
||||
}
|
||||
if distinct.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
findings.push(RuleHit::new(
|
||||
"repeated-container-text",
|
||||
format!(
|
||||
"\"{}\" rendered {}× in distinct spots inside {}",
|
||||
slice_utf16_prefix(text, 40),
|
||||
sigs.len(),
|
||||
class_selector(dom, container)
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
findings
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#checkRepeatedContainerTextDOM()
|
||||
pub fn check_repeated_container_text_dom(dom: &dyn Dom) -> Vec<RuleHit> {
|
||||
collect_repeated_container_text_findings(dom, &|el| is_rendered_for_browser_rule(dom, el))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::browser::fake_dom::FakeDom;
|
||||
|
||||
#[test]
|
||||
fn kicker_above_heading_collects_tracked_caps_label() {
|
||||
let mut d = FakeDom::new();
|
||||
let (_html, body) = d.with_page();
|
||||
let sec = d.add(Some(body), "section");
|
||||
let kicker = d.add(Some(sec), "p");
|
||||
d.add_text(kicker, " Features ");
|
||||
d.set_styles(
|
||||
kicker,
|
||||
&[
|
||||
("fontSize", "12px"),
|
||||
("letterSpacing", "1.2px"),
|
||||
("textTransform", "uppercase"),
|
||||
("fontVariant", "normal"),
|
||||
("fontVariantCaps", "normal"),
|
||||
],
|
||||
);
|
||||
let h = d.add(Some(sec), "h2");
|
||||
d.add_text(h, "Everything you need");
|
||||
d.set_style(h, "fontSize", "32px");
|
||||
let hits = check_kicker_above_heading_dom(&d);
|
||||
assert_eq!(hits.len(), 1);
|
||||
assert_eq!(hits[0].id, "kicker-above-heading");
|
||||
assert_eq!(
|
||||
hits[0].snippet,
|
||||
"kicker \"Features\" above h2 \"Everything you need\""
|
||||
);
|
||||
// A card context (heading inside <article> that also contains the
|
||||
// kicker) stands down.
|
||||
let art = d.add(Some(body), "article");
|
||||
let k2 = d.add(Some(art), "p");
|
||||
d.add_text(k2, "NEWS");
|
||||
d.set_styles(k2, &[("fontSize", "12px"), ("letterSpacing", "1.2px")]);
|
||||
let h2 = d.add(Some(art), "h3");
|
||||
d.add_text(h2, "Card heading");
|
||||
d.set_style(h2, "fontSize", "24px");
|
||||
assert_eq!(check_kicker_above_heading_dom(&d).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbered_labels_need_two_distinct_indices() {
|
||||
let mut d = FakeDom::new();
|
||||
let (_html, body) = d.with_page();
|
||||
for (i, idx) in ["01", "02"].iter().enumerate() {
|
||||
let sec = d.add(Some(body), "section");
|
||||
let label = d.add(Some(sec), "span");
|
||||
d.add_text(label, idx);
|
||||
d.set_styles(
|
||||
label,
|
||||
&[
|
||||
("fontSize", "11px"),
|
||||
("letterSpacing", "1px"),
|
||||
("fontWeight", "700"),
|
||||
("fontFamily", "monospace"),
|
||||
("textTransform", "none"),
|
||||
("color", "rgb(0, 0, 0)"),
|
||||
],
|
||||
);
|
||||
let h = d.add(Some(sec), "h2");
|
||||
d.add_text(h, &format!("Section number {}", i + 1));
|
||||
d.set_style(h, "fontSize", "28px");
|
||||
}
|
||||
let hits = check_numbered_section_labels_dom(&d);
|
||||
assert_eq!(hits.len(), 2);
|
||||
assert_eq!(
|
||||
hits[0].snippet,
|
||||
"tiny numbered label \"01\" beside h2 \"Section number 1\" (2 on page)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn em_dash_uses_inner_text_then_text_content() {
|
||||
let mut d = FakeDom::new();
|
||||
let (_html, body) = d.with_page();
|
||||
let dashes = "a — b — c — d — e — f — g — h — i";
|
||||
d.add_text(body, dashes);
|
||||
let hits = check_em_dash_overuse_dom(&d);
|
||||
assert_eq!(hits.len(), 1);
|
||||
assert_eq!(hits[0].snippet, "8 em-dashes in body text");
|
||||
d.el_mut(body).inner_text = Some("no dashes here".to_string());
|
||||
assert!(check_em_dash_overuse_dom(&d).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_text_in_card_at_three_distinct_positions() {
|
||||
let mut d = FakeDom::new();
|
||||
let (_html, body) = d.with_page();
|
||||
let card = d.add(Some(body), "div");
|
||||
d.set_attr(card, "class", "card");
|
||||
d.set_styles(
|
||||
card,
|
||||
&[
|
||||
("boxShadow", "rgba(0, 0, 0, 0.1) 0px 2px 4px"),
|
||||
("borderTopWidth", "0px"),
|
||||
("borderRightWidth", "0px"),
|
||||
("borderBottomWidth", "0px"),
|
||||
("borderLeftWidth", "0px"),
|
||||
("borderRadius", "8px"),
|
||||
("backgroundColor", "rgb(255, 255, 255)"),
|
||||
],
|
||||
);
|
||||
for tag in ["p", "span", "em"] {
|
||||
let e = d.add(Some(card), tag);
|
||||
d.add_text(e, "Active");
|
||||
}
|
||||
let hits = check_repeated_container_text_dom(&d);
|
||||
assert_eq!(hits.len(), 1);
|
||||
// classSelector is fork A's (element_checks); the stub yields the
|
||||
// bare tag, the real one "div.card".
|
||||
assert!(hits[0]
|
||||
.snippet
|
||||
.starts_with("\"Active\" rendered 3× in distinct spots inside div"));
|
||||
// Parallel positions (same signature) do not count.
|
||||
let mut d2 = FakeDom::new();
|
||||
let (_h, b2) = d2.with_page();
|
||||
let card2 = d2.add(Some(b2), "div");
|
||||
d2.set_styles(
|
||||
card2,
|
||||
&[
|
||||
("boxShadow", "rgba(0, 0, 0, 0.1) 0px 2px 4px"),
|
||||
("borderRadius", "8px"),
|
||||
("backgroundColor", "rgb(255, 255, 255)"),
|
||||
],
|
||||
);
|
||||
for _ in 0..3 {
|
||||
let e = d2.add(Some(card2), "li");
|
||||
d2.add_text(e, "Active");
|
||||
}
|
||||
assert!(check_repeated_container_text_dom(&d2).is_empty());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,714 @@
|
||||
//! Port of `cli/engine/rules/checks.mjs` page-level regex-on-HTML checks:
|
||||
//! `scanHtmlForShapeAssembledIllustration`, `buildHtmlPatternCorpora`, and
|
||||
//! `checkHtmlPatterns` (the browser / static shared pattern pass).
|
||||
|
||||
use crate::checks::css_scan::{
|
||||
enclosing_css_selector, scan_css_text_for_buried_raster, scan_css_text_for_glow,
|
||||
scan_css_text_for_grid_background, scan_css_text_for_inset_stripe, scan_css_text_for_marquee,
|
||||
scan_css_text_for_organic_clip_path, scan_css_text_for_pseudo_stripe,
|
||||
scan_css_text_for_pulsing_dot, scan_css_text_for_radial_halo, PatternFinding,
|
||||
};
|
||||
use crate::checks::rules::{RuleHit, ANY, B, BEZIER_RE, D, DOT, W};
|
||||
use crate::js::{self, ci, math_round, number_to_string, parse_float, parse_int, WS, WS_CHARS};
|
||||
use crate::js_ext_a::{advance_utf16, is_word_byte, retreat_utf16};
|
||||
use once_cell::sync::Lazy;
|
||||
use regex::Regex;
|
||||
|
||||
/// The corpora type is shared; re-exported so `checks::html_patterns` stays
|
||||
/// one path.
|
||||
pub use impeccable_foundation::rules::html_patterns::*;
|
||||
|
||||
macro_rules! re {
|
||||
($name:ident, $pat:expr) => {
|
||||
static $name: Lazy<Regex> = Lazy::new(|| Regex::new(&$pat).expect(stringify!($name)));
|
||||
};
|
||||
}
|
||||
|
||||
// ─── scanHtmlForShapeAssembledIllustration ──────────────────────────────────
|
||||
|
||||
re!(
|
||||
SVG_BLOCK_RE,
|
||||
format!(r"<{svg}{B}[^>]*>{ANY}*?</{svg}>", svg = ci("svg"))
|
||||
);
|
||||
re!(SVG_OPEN_RE, format!(r"^<{svg}{B}[^>]*>", svg = ci("svg")));
|
||||
re!(
|
||||
SVG_TEXT_RE,
|
||||
format!(
|
||||
r"<(?:{text}|{tspan}){B}",
|
||||
text = ci("text"),
|
||||
tspan = ci("tspan")
|
||||
)
|
||||
);
|
||||
re!(SVG_PATTERN_RE, format!(r"<{}{B}", ci("pattern")));
|
||||
re!(
|
||||
SVG_PRIMITIVE_RE,
|
||||
format!(
|
||||
r"<(?:{rect}|{circle}|{ellipse}|{polygon}){B}",
|
||||
rect = ci("rect"),
|
||||
circle = ci("circle"),
|
||||
ellipse = ci("ellipse"),
|
||||
polygon = ci("polygon")
|
||||
)
|
||||
);
|
||||
re!(
|
||||
SVG_VIEWBOX_RE,
|
||||
format!(
|
||||
r#"{B}{vb}{WS}*={WS}*["']{WS}*[-0-9.]+[{WS_CHARS},]+[-0-9.]+[{WS_CHARS},]+([0-9.]+)[{WS_CHARS},]+([0-9.]+){WS}*["']"#,
|
||||
vb = ci("viewBox")
|
||||
)
|
||||
);
|
||||
re!(
|
||||
SVG_FILL_RE,
|
||||
format!(
|
||||
r#"{B}{fill}{WS}*[:=]{WS}*["']?{WS}*([^"';>}}{WS_CHARS}]+)"#,
|
||||
fill = ci("fill")
|
||||
)
|
||||
);
|
||||
re!(
|
||||
SVG_WIDTH_RE,
|
||||
format!(
|
||||
r#"{w}{WS}*={WS}*["']{WS}*([0-9.]+)(?:{px})?{WS}*["']"#,
|
||||
w = ci("width"),
|
||||
px = ci("px")
|
||||
)
|
||||
);
|
||||
re!(
|
||||
SVG_HEIGHT_RE,
|
||||
format!(
|
||||
r#"{h}{WS}*={WS}*["']{WS}*([0-9.]+)(?:{px})?{WS}*["']"#,
|
||||
h = ci("height"),
|
||||
px = ci("px")
|
||||
)
|
||||
);
|
||||
|
||||
/// JS `attrDim(name)`: first `name="<num>"` in the open tag whose match is
|
||||
/// not preceded by `[-\w]` (the lookbehind keeps `stroke-width` out).
|
||||
fn svg_attr_dim(open_tag: &str, re: &Regex) -> Option<f64> {
|
||||
for m in re.captures_iter(open_tag) {
|
||||
let start = m.get(0).unwrap().start();
|
||||
let preceded = start > 0 && {
|
||||
let b = open_tag.as_bytes()[start - 1];
|
||||
b == b'-' || is_word_byte(b)
|
||||
};
|
||||
if preceded {
|
||||
continue;
|
||||
}
|
||||
return Some(parse_float(&m[1]));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#scanHtmlForShapeAssembledIllustration
|
||||
pub fn scan_html_for_shape_assembled_illustration(html: &str) -> Vec<RuleHit> {
|
||||
let mut findings = Vec::new();
|
||||
for m in SVG_BLOCK_RE.find_iter(html) {
|
||||
let block = m.as_str();
|
||||
let open_tag = SVG_OPEN_RE.find(block).map(|o| o.as_str()).unwrap_or("");
|
||||
let text_count = SVG_TEXT_RE.find_iter(block).count();
|
||||
if text_count > 2 {
|
||||
continue;
|
||||
}
|
||||
if SVG_PATTERN_RE.is_match(block) {
|
||||
continue;
|
||||
}
|
||||
let primitives = SVG_PRIMITIVE_RE.find_iter(block).count();
|
||||
if primitives < 8 {
|
||||
continue;
|
||||
}
|
||||
let vb = SVG_VIEWBOX_RE.captures(open_tag);
|
||||
let w = svg_attr_dim(open_tag, &SVG_WIDTH_RE)
|
||||
.or_else(|| vb.as_ref().map(|v| parse_float(&v[1])));
|
||||
let h = svg_attr_dim(open_tag, &SVG_HEIGHT_RE)
|
||||
.or_else(|| vb.as_ref().map(|v| parse_float(&v[2])));
|
||||
let (w, h) = match (w, h) {
|
||||
(Some(w), Some(h)) => (w, h),
|
||||
_ => continue,
|
||||
};
|
||||
if w < 200.0 || h < 200.0 {
|
||||
continue;
|
||||
}
|
||||
let mut fills: Vec<String> = Vec::new();
|
||||
for fm in SVG_FILL_RE.captures_iter(block) {
|
||||
let paint = js::to_lower_case(js::trim(&fm[1]));
|
||||
if paint.is_empty()
|
||||
|| matches!(
|
||||
paint.as_str(),
|
||||
"none" | "transparent" | "currentcolor" | "inherit"
|
||||
)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if !fills.contains(&paint) {
|
||||
fills.push(paint);
|
||||
}
|
||||
}
|
||||
if fills.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
findings.push(RuleHit::new(
|
||||
"shape-assembled-illustration",
|
||||
format!(
|
||||
"inline <svg> scene: {} primitive shapes, ~{}x{}px, {} fill colors",
|
||||
primitives,
|
||||
number_to_string(math_round(w)),
|
||||
number_to_string(math_round(h)),
|
||||
fills.len()
|
||||
),
|
||||
));
|
||||
}
|
||||
findings
|
||||
}
|
||||
|
||||
// ─── buildHtmlPatternCorpora ────────────────────────────────────────────────
|
||||
|
||||
re!(HAS_MARKUP_RE, r"<[a-zA-Z!/]".to_string());
|
||||
re!(
|
||||
STYLE_BLOCK_RE,
|
||||
format!(r"<{style}{B}[^>]*>({ANY}*?)</{style}>", style = ci("style"))
|
||||
);
|
||||
re!(TAG_RE, r"<[a-zA-Z][^>]*>".to_string());
|
||||
re!(
|
||||
STYLE_ATTR_RE,
|
||||
format!(
|
||||
r#"{B}{style}{WS}*={WS}*("[^"]*"|'[^']*')"#,
|
||||
style = ci("style")
|
||||
)
|
||||
);
|
||||
re!(
|
||||
CLASS_ATTR_IN_TAG_RE,
|
||||
format!(
|
||||
r#"{B}{cls}{WS}*={WS}*(?:"([^"]*)"|'([^']*)')"#,
|
||||
cls = ci("class")
|
||||
)
|
||||
);
|
||||
|
||||
/// JS: checks.mjs#buildHtmlPatternCorpora
|
||||
pub fn build_html_pattern_corpora(html: &str) -> HtmlPatternCorpora {
|
||||
if !HAS_MARKUP_RE.is_match(html) {
|
||||
return HtmlPatternCorpora {
|
||||
style_text: html.to_string(),
|
||||
class_text: html.to_string(),
|
||||
};
|
||||
}
|
||||
let mut style_parts: Vec<String> = Vec::new();
|
||||
let mut class_parts: Vec<String> = Vec::new();
|
||||
for m in STYLE_BLOCK_RE.captures_iter(html) {
|
||||
style_parts.push(m[1].to_string());
|
||||
}
|
||||
for t in TAG_RE.find_iter(html) {
|
||||
let tag = t.as_str();
|
||||
if let Some(sm) = STYLE_ATTR_RE.captures(tag) {
|
||||
style_parts.push(format!("style={}", &sm[1]));
|
||||
}
|
||||
if let Some(cm) = CLASS_ATTR_IN_TAG_RE.captures(tag) {
|
||||
let v = cm
|
||||
.get(1)
|
||||
.or_else(|| cm.get(2))
|
||||
.map(|g| g.as_str())
|
||||
.unwrap_or("");
|
||||
class_parts.push(v.to_string());
|
||||
}
|
||||
}
|
||||
HtmlPatternCorpora {
|
||||
style_text: style_parts.join("\n"),
|
||||
class_text: class_parts.join("\n"),
|
||||
}
|
||||
}
|
||||
|
||||
// ─── checkHtmlPatterns ──────────────────────────────────────────────────────
|
||||
|
||||
const PURPLE_HEX_ALT: &str = "7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea";
|
||||
fn ci_alt(alts: &str) -> String {
|
||||
alts.split('|').map(ci).collect::<Vec<_>>().join("|")
|
||||
}
|
||||
static PURPLE_HEX_RE: Lazy<Regex> = Lazy::new(|| {
|
||||
Regex::new(&format!(r"#(?:{}){B}", ci_alt(PURPLE_HEX_ALT))).expect("PURPLE_HEX_RE")
|
||||
});
|
||||
static PURPLE_TEXT_RE: Lazy<Regex> = Lazy::new(|| {
|
||||
Regex::new(&format!(
|
||||
r"(?:(?:^|;){WS}*{color}{WS}*:{WS}*(?:{DOT}*?)(?:#(?:{a}))|{gradient}{DOT}*?#(?:{b}))",
|
||||
color = ci("color"),
|
||||
gradient = ci("gradient"),
|
||||
a = ci_alt("7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9"),
|
||||
b = ci_alt("7c3aed|8b5cf6|a855f7|764ba2|667eea")
|
||||
))
|
||||
.expect("PURPLE_TEXT_RE")
|
||||
});
|
||||
re!(
|
||||
BG_CLIP_TEXT_RE,
|
||||
format!(
|
||||
r"(?:-webkit-)?{bct}{WS}*:{WS}*{text}",
|
||||
bct = ci("background-clip"),
|
||||
text = ci("text")
|
||||
)
|
||||
);
|
||||
re!(GRADIENT_CI_RE, ci("gradient"));
|
||||
re!(TW_BG_CLIP_TEXT_RE, format!(r"{B}bg-clip-text{B}"));
|
||||
re!(TW_BG_GRADIENT_TO_RE, format!(r"{B}bg-gradient-to-"));
|
||||
re!(
|
||||
SPACING_PX_RE,
|
||||
format!(
|
||||
r"(?:{padding}|{margin})(?:-(?:{top}|{right}|{bottom}|{left}))?{WS}*:{WS}*({D}+)px",
|
||||
padding = ci("padding"),
|
||||
margin = ci("margin"),
|
||||
top = ci("top"),
|
||||
right = ci("right"),
|
||||
bottom = ci("bottom"),
|
||||
left = ci("left")
|
||||
)
|
||||
);
|
||||
re!(
|
||||
GAP_PX_RE,
|
||||
format!(r"{gap}{WS}*:{WS}*({D}+)px", gap = ci("gap"))
|
||||
);
|
||||
re!(
|
||||
TW_SPACE_RE,
|
||||
format!(r"{B}(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-({D}+){B}")
|
||||
);
|
||||
re!(
|
||||
SPACING_REM_RE,
|
||||
format!(
|
||||
r"(?:{padding}|{margin})(?:-(?:{top}|{right}|{bottom}|{left}))?{WS}*:{WS}*([0-9.]+){rem}",
|
||||
padding = ci("padding"),
|
||||
margin = ci("margin"),
|
||||
top = ci("top"),
|
||||
right = ci("right"),
|
||||
bottom = ci("bottom"),
|
||||
left = ci("left"),
|
||||
rem = ci("rem")
|
||||
)
|
||||
);
|
||||
re!(
|
||||
BOUNCE_ANIM_RE,
|
||||
format!(
|
||||
r"{animation}(?:-{name})?{WS}*:{WS}*([^;{{}}]*(?:{bounce}|{elastic}|{wobble}|{jiggle}|{spring})[^;{{}}]*)",
|
||||
animation = ci("animation"),
|
||||
name = ci("name"),
|
||||
bounce = ci("bounce"),
|
||||
elastic = ci("elastic"),
|
||||
wobble = ci("wobble"),
|
||||
jiggle = ci("jiggle"),
|
||||
spring = ci("spring")
|
||||
)
|
||||
);
|
||||
re!(
|
||||
BOUNCE_WORD_RE,
|
||||
format!(
|
||||
"{}|{}|{}|{}|{}",
|
||||
ci("bounce"),
|
||||
ci("elastic"),
|
||||
ci("wobble"),
|
||||
ci("jiggle"),
|
||||
ci("spring")
|
||||
)
|
||||
);
|
||||
re!(COMMA_WS_SPLIT_RE, format!(r"[,{WS_CHARS}]+"));
|
||||
re!(
|
||||
TRANSITION_RE,
|
||||
format!(
|
||||
r"{transition}(?:-{property})?{WS}*:{WS}*([^;{{}}]+)",
|
||||
transition = ci("transition"),
|
||||
property = ci("property")
|
||||
)
|
||||
);
|
||||
re!(ALL_WORD_RE, format!(r"{B}all{B}"));
|
||||
re!(
|
||||
LAYOUT_PROP_RE,
|
||||
format!(
|
||||
r"{B}(?:(?:{max}|{min})-)?(?:{width}|{height}){B}|{B}{padding}(?:-(?:{top}|{right}|{bottom}|{left}))?{B}|{B}{margin}(?:-(?:{top}|{right}|{bottom}|{left}))?{B}",
|
||||
max = ci("max"),
|
||||
min = ci("min"),
|
||||
width = ci("width"),
|
||||
height = ci("height"),
|
||||
padding = ci("padding"),
|
||||
margin = ci("margin"),
|
||||
top = ci("top"),
|
||||
right = ci("right"),
|
||||
bottom = ci("bottom"),
|
||||
left = ci("left")
|
||||
)
|
||||
);
|
||||
re!(
|
||||
REPEATING_GRADIENT_RE,
|
||||
format!(
|
||||
r"{repeating}-(?:{linear}|{radial}|{conic})-{gradient}{WS}*\(",
|
||||
repeating = ci("repeating"),
|
||||
linear = ci("linear"),
|
||||
radial = ci("radial"),
|
||||
conic = ci("conic"),
|
||||
gradient = ci("gradient")
|
||||
)
|
||||
);
|
||||
re!(
|
||||
SCRIPT_BLOCK_RE,
|
||||
format!(
|
||||
r"<{script}{B}[^>]*>{ANY}*?</{script}>",
|
||||
script = ci("script")
|
||||
)
|
||||
);
|
||||
re!(
|
||||
STYLE_BLOCK_STRIP_RE,
|
||||
format!(r"<{style}{B}[^>]*>{ANY}*?</{style}>", style = ci("style"))
|
||||
);
|
||||
re!(ANY_TAG_RE, r"<[^>]+>".to_string());
|
||||
re!(
|
||||
THEATER_RE,
|
||||
format!(r"{B}({W}+){WS}+{theater}{B}", theater = ci("theater"))
|
||||
);
|
||||
re!(
|
||||
IMG_HOVER_CSS_RE,
|
||||
format!(
|
||||
r"{B}{img}{B}[^,{{}}]*:{hover}{B}[^{{}}]*\{{[^}}]*{B}{transform}{WS}*:{WS}*(?:{scale}|{rotate}|{translate}|{matrix}|{skew})",
|
||||
img = ci("img"),
|
||||
hover = ci("hover"),
|
||||
transform = ci("transform"),
|
||||
scale = ci("scale"),
|
||||
rotate = ci("rotate"),
|
||||
translate = ci("translate"),
|
||||
matrix = ci("matrix"),
|
||||
skew = ci("skew")
|
||||
)
|
||||
);
|
||||
re!(
|
||||
IMG_TAG_CLASS_RE,
|
||||
format!(
|
||||
r#"<{img}{B}[^>]*{B}{cls}{WS}*={WS}*"([^"]*)""#,
|
||||
img = ci("img"),
|
||||
cls = ci("class")
|
||||
)
|
||||
);
|
||||
re!(
|
||||
TW_HOVER_TRANSFORM_RE,
|
||||
format!(r"{B}hover:(?:scale|rotate|translate|skew)-")
|
||||
);
|
||||
|
||||
fn pf(id: &str, snippet: String, selector: Option<String>) -> PatternFinding {
|
||||
PatternFinding {
|
||||
id: id.to_string(),
|
||||
snippet,
|
||||
selector,
|
||||
index: None,
|
||||
severity: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#checkHtmlPatterns. `corpora` defaults to
|
||||
/// `buildHtmlPatternCorpora(html)`. Findings' `index` fields are byte
|
||||
/// offsets into `corpora.style_text`.
|
||||
pub fn check_html_patterns(
|
||||
html: &str,
|
||||
corpora: Option<&HtmlPatternCorpora>,
|
||||
) -> Vec<PatternFinding> {
|
||||
let built;
|
||||
let corpora = match corpora {
|
||||
Some(c) => c,
|
||||
None => {
|
||||
built = build_html_pattern_corpora(html);
|
||||
&built
|
||||
}
|
||||
};
|
||||
let style_text = corpora.style_text.as_str();
|
||||
let class_text = corpora.class_text.as_str();
|
||||
let mut findings: Vec<PatternFinding> = Vec::new();
|
||||
|
||||
// --- Color ---
|
||||
if PURPLE_HEX_RE.is_match(style_text) {
|
||||
if let Some(pm) = PURPLE_TEXT_RE.find(style_text) {
|
||||
let idx = advance_utf16(style_text, pm.start(), 1);
|
||||
findings.push(pf(
|
||||
"ai-color-palette",
|
||||
"Purple/violet accent colors detected".to_string(),
|
||||
enclosing_css_selector(style_text, idx),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
for gm in BG_CLIP_TEXT_RE.find_iter(style_text) {
|
||||
let start = retreat_utf16(style_text, gm.start(), 200);
|
||||
let end = advance_utf16(style_text, gm.end(), 200);
|
||||
let context = &style_text[start..end];
|
||||
if GRADIENT_CI_RE.is_match(context) {
|
||||
findings.push(pf(
|
||||
"gradient-text",
|
||||
"background-clip: text + gradient".to_string(),
|
||||
enclosing_css_selector(style_text, gm.start()),
|
||||
));
|
||||
break;
|
||||
}
|
||||
}
|
||||
if TW_BG_CLIP_TEXT_RE.is_match(class_text) && TW_BG_GRADIENT_TO_RE.is_match(class_text) {
|
||||
findings.push(pf(
|
||||
"gradient-text",
|
||||
"bg-clip-text + bg-gradient (Tailwind)".to_string(),
|
||||
None,
|
||||
));
|
||||
}
|
||||
|
||||
// --- Borders ---
|
||||
findings.extend(scan_css_text_for_pseudo_stripe(style_text));
|
||||
findings.extend(scan_css_text_for_inset_stripe(style_text));
|
||||
|
||||
// --- Layout ---
|
||||
let mut spacing_values: Vec<f64> = Vec::new();
|
||||
for sm in SPACING_PX_RE.captures_iter(style_text) {
|
||||
let v = parse_int(&sm[1], 10);
|
||||
if v > 0.0 && v < 200.0 {
|
||||
spacing_values.push(v);
|
||||
}
|
||||
}
|
||||
for sm in GAP_PX_RE.captures_iter(style_text) {
|
||||
spacing_values.push(parse_int(&sm[1], 10));
|
||||
}
|
||||
for sm in TW_SPACE_RE.captures_iter(class_text) {
|
||||
spacing_values.push(parse_int(&sm[1], 10) * 4.0);
|
||||
}
|
||||
for sm in SPACING_REM_RE.captures_iter(style_text) {
|
||||
let v = math_round(parse_float(&sm[1]) * 16.0);
|
||||
if v > 0.0 && v < 200.0 {
|
||||
spacing_values.push(v);
|
||||
}
|
||||
}
|
||||
let rounded_spacing: Vec<f64> = spacing_values
|
||||
.iter()
|
||||
.map(|v| math_round(v / 4.0) * 4.0)
|
||||
.collect();
|
||||
if rounded_spacing.len() >= 10 {
|
||||
// `counts` as a JS object: keys are `String(v)`.
|
||||
let mut counts: Vec<(String, f64, usize)> = Vec::new(); // (key, numeric, count)
|
||||
for &v in &rounded_spacing {
|
||||
let key = number_to_string(v);
|
||||
if let Some(slot) = counts.iter_mut().find(|(k, _, _)| *k == key) {
|
||||
slot.2 += 1;
|
||||
} else {
|
||||
counts.push((key, v, 1));
|
||||
}
|
||||
}
|
||||
let max_count = counts.iter().map(|c| c.2).max().unwrap_or(0);
|
||||
let dominant_pct = max_count as f64 / rounded_spacing.len() as f64;
|
||||
// `[...new Set(roundedSpacing)].filter(v => v > 0)`
|
||||
let mut unique: Vec<f64> = Vec::new();
|
||||
for &v in &rounded_spacing {
|
||||
if !unique.iter().any(|u| (u.is_nan() && v.is_nan()) || *u == v) {
|
||||
unique.push(v);
|
||||
}
|
||||
}
|
||||
let unique: Vec<f64> = unique.into_iter().filter(|v| *v > 0.0).collect();
|
||||
if dominant_pct > 0.6 && unique.len() <= 3 {
|
||||
// JS sorts `Object.entries(counts)` by count and takes the first;
|
||||
// `dominantPct > 0.6` means the maximum is unique, so entry
|
||||
// order never decides.
|
||||
let dominant = &counts.iter().find(|c| c.2 == max_count).unwrap().0;
|
||||
findings.push(pf(
|
||||
"monotonous-spacing",
|
||||
format!(
|
||||
"~{}px used {}/{} times ({}%)",
|
||||
dominant,
|
||||
max_count,
|
||||
rounded_spacing.len(),
|
||||
number_to_string(math_round(dominant_pct * 100.0))
|
||||
),
|
||||
None,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Motion ---
|
||||
if let Some(bm) = BOUNCE_ANIM_RE.captures(style_text) {
|
||||
let list = &bm[1];
|
||||
let token = COMMA_WS_SPLIT_RE
|
||||
.split(list)
|
||||
.find(|part| BOUNCE_WORD_RE.is_match(part));
|
||||
let label = match token {
|
||||
Some(t) if !t.is_empty() => t.to_string(),
|
||||
_ => js::trim(list).to_string(),
|
||||
};
|
||||
findings.push(pf(
|
||||
"bounce-easing",
|
||||
format!("animation: {}", label),
|
||||
enclosing_css_selector(style_text, bm.get(0).unwrap().start()),
|
||||
));
|
||||
}
|
||||
|
||||
for bm in BEZIER_RE.captures_iter(style_text) {
|
||||
let y1 = parse_float(&bm[2]);
|
||||
let y2 = parse_float(&bm[4]);
|
||||
if y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1 {
|
||||
findings.push(pf(
|
||||
"bounce-easing",
|
||||
format!(
|
||||
"cubic-bezier({}, {}, {}, {})",
|
||||
&bm[1], &bm[2], &bm[3], &bm[4]
|
||||
),
|
||||
enclosing_css_selector(style_text, bm.get(0).unwrap().start()),
|
||||
));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for tm in TRANSITION_RE.captures_iter(style_text) {
|
||||
let val = js::to_lower_case(&tm[1]);
|
||||
if ALL_WORD_RE.is_match(&val) {
|
||||
continue;
|
||||
}
|
||||
let found: Vec<&str> = LAYOUT_PROP_RE.find_iter(&val).map(|m| m.as_str()).collect();
|
||||
if !found.is_empty() {
|
||||
findings.push(pf(
|
||||
"layout-transition",
|
||||
format!("transition: {}", found.join(", ")),
|
||||
None,
|
||||
));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
findings.extend(scan_css_text_for_pulsing_dot(style_text, Some(html)));
|
||||
findings.extend(
|
||||
scan_html_for_shape_assembled_illustration(html)
|
||||
.into_iter()
|
||||
.map(|h| pf(&h.id, h.snippet, None)),
|
||||
);
|
||||
|
||||
// Organic clip-path contours and rasters buried under washes or opacity
|
||||
findings.extend(scan_css_text_for_organic_clip_path(style_text));
|
||||
findings.extend(scan_css_text_for_buried_raster(style_text));
|
||||
|
||||
findings.extend(scan_css_text_for_marquee(style_text, Some(html)));
|
||||
|
||||
// --- Dark glow / chromatic halo shadows ---
|
||||
let glow_hits = scan_css_text_for_glow(style_text);
|
||||
if let Some(first) = glow_hits.first() {
|
||||
findings.push(pf(
|
||||
"dark-glow",
|
||||
first.snippet.clone(),
|
||||
enclosing_css_selector(style_text, first.index),
|
||||
));
|
||||
}
|
||||
let halo_hits = scan_css_text_for_radial_halo(style_text);
|
||||
if let Some(first) = halo_hits.first() {
|
||||
findings.push(pf(
|
||||
"radial-halo",
|
||||
first.snippet.clone(),
|
||||
enclosing_css_selector(style_text, first.index),
|
||||
));
|
||||
}
|
||||
|
||||
// --- Generated-UI tells: repeating-gradient stripes ---
|
||||
if let Some(sm) = REPEATING_GRADIENT_RE.find(style_text) {
|
||||
findings.push(pf(
|
||||
"repeating-stripes-gradient",
|
||||
"repeating-gradient decorative stripes".to_string(),
|
||||
enclosing_css_selector(style_text, sm.start()),
|
||||
));
|
||||
}
|
||||
|
||||
// --- Generated-UI tells: two-axis grid-line background ---
|
||||
let grid_hits = scan_css_text_for_grid_background(style_text);
|
||||
if let Some(first) = grid_hits.first() {
|
||||
findings.push(pf(
|
||||
"codex-grid-background",
|
||||
first.snippet.clone(),
|
||||
enclosing_css_selector(style_text, first.index),
|
||||
));
|
||||
}
|
||||
|
||||
// --- Generated-copy tells: "X theater" framing copy ---
|
||||
{
|
||||
let no_script = SCRIPT_BLOCK_RE.replace_all(html, " ");
|
||||
let no_style = STYLE_BLOCK_STRIP_RE.replace_all(&no_script, " ");
|
||||
let body_text = ANY_TAG_RE.replace_all(&no_style, " ");
|
||||
if let Some(tm) = THEATER_RE.find(&body_text) {
|
||||
findings.push(pf(
|
||||
"theater-slop-phrase",
|
||||
format!("\"{}\"", js::trim(tm.as_str())),
|
||||
None,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Generated-UI tells: image hover transform ---
|
||||
if let Some(im) = IMG_HOVER_CSS_RE.find(style_text) {
|
||||
let brace = im.as_str().find('{').unwrap_or(0);
|
||||
findings.push(pf(
|
||||
"image-hover-transform",
|
||||
"img:hover { transform } rule".to_string(),
|
||||
enclosing_css_selector(style_text, im.start() + brace + 1),
|
||||
));
|
||||
}
|
||||
for im in IMG_TAG_CLASS_RE.captures_iter(html) {
|
||||
if TW_HOVER_TRANSFORM_RE.is_match(&im[1]) {
|
||||
findings.push(pf(
|
||||
"image-hover-transform",
|
||||
"Tailwind hover transform on <img>".to_string(),
|
||||
None,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
findings
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Expected values come from running the JS functions in Node.
|
||||
|
||||
#[test]
|
||||
fn corpora_match_node() {
|
||||
let c = build_html_pattern_corpora("a{b:c}");
|
||||
assert_eq!(
|
||||
(c.style_text.as_str(), c.class_text.as_str()),
|
||||
("a{b:c}", "a{b:c}")
|
||||
);
|
||||
let c = build_html_pattern_corpora(
|
||||
"<style>.a{b:c}</style><div style=\"x:y\" class=\"p q\"><span class='r'>t</span></div><p STYLE='m:n'><div style=\"z\"></p>",
|
||||
);
|
||||
assert_eq!(c.style_text, ".a{b:c}\nstyle=\"x:y\"\nstyle='m:n'");
|
||||
assert_eq!(c.class_text, "p q\nr");
|
||||
let c = build_html_pattern_corpora("<!-- x --><div>");
|
||||
assert_eq!((c.style_text.as_str(), c.class_text.as_str()), ("", ""));
|
||||
let c = build_html_pattern_corpora("<style>a</style><style>b</style>");
|
||||
assert_eq!(c.style_text, "a\nb");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_attr_dim_lookbehind() {
|
||||
let scene = "<rect fill=\"red\"/><rect fill=\"blue\"/><rect fill=\"#0f0\"/><circle/><circle/><circle/><ellipse/><polygon/></svg>";
|
||||
let hits = scan_html_for_shape_assembled_illustration(&format!(
|
||||
"<svg stroke-width=\"1\" viewBox=\"0 0 400 300\">{scene}"
|
||||
));
|
||||
assert_eq!(
|
||||
hits[0].snippet,
|
||||
"inline <svg> scene: 8 primitive shapes, ~400x300px, 3 fill colors"
|
||||
);
|
||||
assert!(scan_html_for_shape_assembled_illustration(&format!(
|
||||
"<svg stroke-width=\"1\" width=\"100\" viewBox=\"0 0 400 300\">{scene}"
|
||||
))
|
||||
.is_empty());
|
||||
let nan = scan_html_for_shape_assembled_illustration(&format!(
|
||||
"<svg width=\".\" height=\".\">{scene}"
|
||||
));
|
||||
assert_eq!(
|
||||
nan[0].snippet,
|
||||
"inline <svg> scene: 8 primitive shapes, ~NaNxNaNpx, 3 fill colors"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spacing_and_theater_match_node() {
|
||||
let out = check_html_patterns(
|
||||
"<style>.a{padding:8px;margin:8px;gap:8px;padding-top:8px;margin-left:8px;padding:8px;margin:0.5rem;gap:5000000000px;padding:9px}</style><p class=\"p-2 gap-2\">security theater here</p>",
|
||||
None,
|
||||
);
|
||||
let snippets: Vec<&str> = out.iter().map(|f| f.snippet.as_str()).collect();
|
||||
assert_eq!(
|
||||
snippets,
|
||||
vec!["~8px used 10/11 times (91%)", "\"security theater\""]
|
||||
);
|
||||
let out = check_html_patterns(
|
||||
"<style>.a{padding:8px;margin:8px;gap:8px;padding-top:8px;margin-left:8px;padding:8px;margin:0.5rem;gap:8px;padding:9px;gap:9px;gap:9px}</style>",
|
||||
None,
|
||||
);
|
||||
assert_eq!(out[0].snippet, "~8px used 11/11 times (100%)");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,661 @@
|
||||
//! Port of cli/engine/rules/checks.mjs (see checks/mod.rs for the split):
|
||||
//! the plain-data helpers and pure gates of Sections 4-6. Element / document
|
||||
//! adapters live in the `html` crate.
|
||||
//!
|
||||
//! Style-reading helpers take a [`StyleMap`]: any lookup from the JS
|
||||
//! camelCase computed-style property name (`borderTopWidth`, `clipPath`) to
|
||||
//! its string value, so a jsdom-style map, a real cascade, and a test
|
||||
//! `HashMap` all fit.
|
||||
|
||||
use crate::color::{self, Rgba};
|
||||
|
||||
use crate::js::{self, math_max, math_min3, math_round, number_to_string, to_fixed, WS, WS_CHARS};
|
||||
|
||||
use crate::js_ext_b::{slice_utf16_prefix, utf16_len};
|
||||
|
||||
use once_cell::sync::Lazy;
|
||||
use regex::Regex;
|
||||
|
||||
/// The CSS value helpers, style traits and plain-data types these checks are
|
||||
/// written against are shared; re-exported so `checks::measures` stays one path.
|
||||
pub use impeccable_foundation::css::measures::*;
|
||||
|
||||
/// JS `\d` is ASCII only.
|
||||
const D: &str = "[0-9]";
|
||||
|
||||
macro_rules! re {
|
||||
($name:ident, $pat:expr) => {
|
||||
static $name: Lazy<Regex> = Lazy::new(|| Regex::new(&$pat).expect(stringify!($name)));
|
||||
};
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#checkRadialSpotlight. Pure gate; `label` is a stable
|
||||
/// identifier the fixture test keys on.
|
||||
pub fn check_radial_spotlight(input: &RadialSpotlightInput) -> Vec<Finding> {
|
||||
let Some(stops) = parse_radial_gradient_stops(input.gradient_value) else {
|
||||
return vec![];
|
||||
};
|
||||
if stops.len() < 2 {
|
||||
return vec![];
|
||||
}
|
||||
let last = &stops[stops.len() - 1];
|
||||
let last_alpha = if last.transparent {
|
||||
0.0
|
||||
} else {
|
||||
last.color.map(|c| c.alpha_or_one()).unwrap_or(1.0)
|
||||
};
|
||||
if last_alpha > 0.05 {
|
||||
return vec![];
|
||||
}
|
||||
let colored: Vec<&GradientStop> = stops
|
||||
.iter()
|
||||
.filter(|s| !s.transparent && matches!(s.color, Some(c) if c.alpha_or_one() > 0.05))
|
||||
.collect();
|
||||
if colored.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
if colored.len() > 2 {
|
||||
return vec![];
|
||||
}
|
||||
if colored
|
||||
.iter()
|
||||
.any(|s| s.color.map(|c| c.alpha_or_one()).unwrap_or(1.0) >= 0.45)
|
||||
{
|
||||
return vec![];
|
||||
}
|
||||
let Some(chromatic) = colored
|
||||
.iter()
|
||||
.find(|s| color::has_chroma(s.color.as_ref(), Some(24.0)))
|
||||
else {
|
||||
return vec![];
|
||||
};
|
||||
if !(input.width >= 240.0 && input.height >= 160.0) {
|
||||
return vec![];
|
||||
}
|
||||
let cc = chromatic.color.expect("colored stop has a color");
|
||||
let alpha = to_fixed(cc.alpha_or_one(), 2);
|
||||
let name = match input.label {
|
||||
Some(l) if !l.is_empty() => l,
|
||||
_ => "section",
|
||||
};
|
||||
vec![Finding::new(
|
||||
"radial-spotlight-glow",
|
||||
format!(
|
||||
"radial-gradient spotlight glow \"{}\" ({} a{} → transparent) on {}x{} surface",
|
||||
name,
|
||||
color::color_to_hex(Some(&cc)),
|
||||
alpha,
|
||||
number_to_string(math_round(input.width)),
|
||||
number_to_string(math_round(input.height))
|
||||
),
|
||||
)]
|
||||
}
|
||||
|
||||
// ─── Cream / beige palette ──────────────────────────────────────────────────
|
||||
|
||||
/// JS: checks.mjs#isCreamColor. A warm, lightly-tinted off-white.
|
||||
pub fn is_cream_color(rgb: Option<&Rgba>) -> bool {
|
||||
let Some(c) = rgb else { return false };
|
||||
let (r, g, b) = (c.r, c.g, c.b);
|
||||
if math_min3(r, g, b) < 209.0 {
|
||||
return false;
|
||||
}
|
||||
if !(r >= g && g >= b) {
|
||||
return false;
|
||||
}
|
||||
let warmth = r - b;
|
||||
warmth >= 6.0 && warmth <= 48.0
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#creamFromClassList. The Tailwind background token that
|
||||
/// renders as a cream surface, or `None`.
|
||||
pub fn cream_from_class_list(cls: Option<&str>) -> Option<String> {
|
||||
re!(ARB_RE, r"(?-u:\b)bg-\[([^\]]+)\]");
|
||||
let cls = cls?;
|
||||
if cls.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if let Some(arb) = ARB_RE.captures(cls) {
|
||||
let inner = arb.get(1).map(|m| m.as_str()).unwrap_or("");
|
||||
let spaced = inner.replace('_', " ");
|
||||
if is_cream_color(color::parse_any_color(Some(&spaced)).as_ref()) {
|
||||
return Some(format!("bg-[{}]", inner));
|
||||
}
|
||||
}
|
||||
for (tok, hex) in TAILWIND_BG_HEX {
|
||||
let re = Regex::new(&format!(
|
||||
"(?:^|{ws}){}(?:$|{ws})",
|
||||
regex::escape(tok),
|
||||
ws = WS
|
||||
))
|
||||
.expect("tailwind token regex");
|
||||
if re.is_match(cls) && is_cream_color(color::parse_any_color(Some(hex)).as_ref()) {
|
||||
return Some(tok.to_string());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
// ─── Oversized hero headline ────────────────────────────────────────────────
|
||||
const OVERSIZED_H1_FONT_PX: f64 = 72.0;
|
||||
|
||||
const OVERSIZED_H1_MIN_CHARS: usize = 40;
|
||||
const OVERSIZED_H1_MIN_VIEWPORT_HEIGHT_RATIO: f64 = 0.28;
|
||||
const OVERSIZED_H1_MIN_VIEWPORT_AREA_RATIO: f64 = 0.25;
|
||||
|
||||
/// JS: checks.mjs#checkOversizedH1.
|
||||
pub fn check_oversized_h1(input: &OversizedH1Input) -> Vec<Finding> {
|
||||
if input.tag != "h1" {
|
||||
return vec![];
|
||||
}
|
||||
let text_len = utf16_len(input.heading_text);
|
||||
if input.font_size >= OVERSIZED_H1_FONT_PX && text_len >= OVERSIZED_H1_MIN_CHARS {
|
||||
let mut viewport_detail = String::new();
|
||||
if let Some(rect) = input.rect {
|
||||
if input.viewport_width > 0.0 && input.viewport_height > 0.0 {
|
||||
let height_ratio = rect.height / input.viewport_height;
|
||||
let area_ratio =
|
||||
(rect.width * rect.height) / (input.viewport_width * input.viewport_height);
|
||||
let dominates = height_ratio >= OVERSIZED_H1_MIN_VIEWPORT_HEIGHT_RATIO
|
||||
|| area_ratio >= OVERSIZED_H1_MIN_VIEWPORT_AREA_RATIO;
|
||||
if !dominates {
|
||||
return vec![];
|
||||
}
|
||||
viewport_detail =
|
||||
format!(", {}vh", number_to_string(math_round(height_ratio * 100.0)));
|
||||
}
|
||||
}
|
||||
return vec![Finding::new(
|
||||
"oversized-h1",
|
||||
format!(
|
||||
"{}px h1, {} chars{} \"{}\"",
|
||||
number_to_string(math_round(input.font_size)),
|
||||
text_len,
|
||||
viewport_detail,
|
||||
slice_utf16_prefix(input.heading_text, 60)
|
||||
),
|
||||
)];
|
||||
}
|
||||
vec![]
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#checkGptThinBorderWideShadow.
|
||||
pub fn check_gpt_thin_border_wide_shadow(input: &GptBorderShadowInput) -> Vec<Finding> {
|
||||
let mut visible_thin: Vec<f64> = Vec::new();
|
||||
for (index, &width) in input.border_widths.iter().enumerate() {
|
||||
let color = input
|
||||
.border_colors
|
||||
.and_then(|cs| cs.get(index))
|
||||
.and_then(|c| c.as_deref())
|
||||
.filter(|c| !c.is_empty());
|
||||
let alpha = css_color_alpha(color);
|
||||
if width > 0.0 && width <= 1.5 && alpha >= 0.28 {
|
||||
visible_thin.push(width);
|
||||
}
|
||||
}
|
||||
let mut max_border = 0.0f64;
|
||||
for &w in &visible_thin {
|
||||
max_border = math_max(max_border, w);
|
||||
}
|
||||
let blur = shadow_max_blur_px(input.box_shadow, Some(0.12));
|
||||
if visible_thin.len() >= 2 && blur >= 16.0 {
|
||||
return vec![Finding::new(
|
||||
"gpt-thin-border-wide-shadow",
|
||||
format!(
|
||||
"{}px border + {}px shadow blur",
|
||||
number_to_string(max_border),
|
||||
number_to_string(math_round(blur))
|
||||
),
|
||||
)];
|
||||
}
|
||||
vec![]
|
||||
}
|
||||
|
||||
// ─── Clipped overflow / screen-reader-only text ─────────────────────────────
|
||||
|
||||
/// JS: checks.mjs#positionedStyleImpliesEscape. A positioned child's inset
|
||||
/// declarations read as pushing it outside its clipping parent (negative
|
||||
/// offset or a full 100% offset).
|
||||
pub fn positioned_style_implies_escape(style: &dyn StyleMap) -> bool {
|
||||
re!(
|
||||
NEG_RE,
|
||||
format!(r"(?:^|[{ws}(])-+(?:{d}|\.)", ws = WS_CHARS, d = D)
|
||||
);
|
||||
re!(
|
||||
FULL_RE,
|
||||
format!(r"(?:^|[{ws}(])100(?:\.0+)?%", ws = WS_CHARS)
|
||||
);
|
||||
const PROPS: [&str; 11] = [
|
||||
"top",
|
||||
"right",
|
||||
"bottom",
|
||||
"left",
|
||||
"inset",
|
||||
"insetBlock",
|
||||
"insetInline",
|
||||
"insetBlockStart",
|
||||
"insetBlockEnd",
|
||||
"insetInlineStart",
|
||||
"insetInlineEnd",
|
||||
];
|
||||
for prop in PROPS {
|
||||
let Some(v) = style.prop(prop) else { continue };
|
||||
if v.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let value = js::to_lower_case(js::trim(&v));
|
||||
if NEG_RE.is_match(&value) {
|
||||
return true;
|
||||
}
|
||||
if FULL_RE.is_match(&value) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#checkContentHiddenAtRest. Pure threshold check over a
|
||||
/// `measureHiddenTextDOM()` result.
|
||||
pub fn check_content_hidden_at_rest(input: &ContentHiddenInput) -> Vec<Finding> {
|
||||
if input.total_chars < 200.0 || input.hidden_chars < 150.0 {
|
||||
return vec![];
|
||||
}
|
||||
let share = input.hidden_chars / input.total_chars;
|
||||
if share <= 0.3 {
|
||||
return vec![];
|
||||
}
|
||||
let sample = match input.hidden_samples.first() {
|
||||
Some(s) => format!(" (e.g. \"{}\")", s),
|
||||
None => String::new(),
|
||||
};
|
||||
vec![Finding::new(
|
||||
"content-hidden-at-rest",
|
||||
format!(
|
||||
"{}% of page text ({} of {} chars) stays at opacity 0 / visibility hidden after reveal handlers ran{}",
|
||||
number_to_string(math_round(share * 100.0)),
|
||||
number_to_string(input.hidden_chars),
|
||||
number_to_string(input.total_chars),
|
||||
sample
|
||||
),
|
||||
)]
|
||||
}
|
||||
|
||||
// ─── Text occlusion helper ──────────────────────────────────────────────────
|
||||
|
||||
/// JS: checks.mjs#isOpaqueDecoratedBox. A near-solid background fill or
|
||||
/// two-plus visible borders make a box hide whatever sits behind it.
|
||||
pub fn is_opaque_decorated_box(cs: Option<&dyn StyleMap>) -> bool {
|
||||
let Some(cs) = cs else { return false };
|
||||
let bg_raw = prop_or_empty(cs, "backgroundColor");
|
||||
if let Some(bg) = color::parse_any_color(Some(&bg_raw)) {
|
||||
if bg.alpha_or_one() > 0.6 {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
let mut border_sides = 0usize;
|
||||
for side in ["Top", "Right", "Bottom", "Left"] {
|
||||
let w = parse_float_or_zero(cs.prop(&format!("border{}Width", side)).as_deref());
|
||||
if w <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let bc_raw = prop_or_empty(cs, &format!("border{}Color", side));
|
||||
if let Some(bc) = color::parse_any_color(Some(&bc_raw)) {
|
||||
if bc.alpha_or_one() > 0.3 {
|
||||
border_sides += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
border_sides >= 2
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn style(pairs: &[(&str, &str)]) -> HashMap<String, String> {
|
||||
pairs
|
||||
.iter()
|
||||
.map(|(k, v)| (k.to_string(), v.to_string()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
// Expected values below were produced by running the JS functions in Node.
|
||||
|
||||
#[test]
|
||||
fn css_color_is_transparent_cases() {
|
||||
assert!(css_color_is_transparent(None));
|
||||
assert!(css_color_is_transparent(Some("")));
|
||||
assert!(css_color_is_transparent(Some(" Transparent ")));
|
||||
assert!(css_color_is_transparent(Some("rgba(0, 0, 0, 0)")));
|
||||
assert!(css_color_is_transparent(Some("rgba(10,20,30,0.04)")));
|
||||
assert!(!css_color_is_transparent(Some("rgba(10,20,30,0.5)")));
|
||||
assert!(!css_color_is_transparent(Some("#fff")));
|
||||
assert!(css_color_is_transparent(Some("rgba(1, 2, 3, 0.00)")));
|
||||
assert!(!css_color_is_transparent(Some("notacolor")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colors_nearly_match_cases() {
|
||||
assert!(colors_nearly_match(
|
||||
Some("#fff"),
|
||||
Some("rgb(254, 255, 253)")
|
||||
));
|
||||
assert!(!colors_nearly_match(
|
||||
Some("#fff"),
|
||||
Some("rgb(250, 255, 255)")
|
||||
));
|
||||
assert!(!colors_nearly_match(Some("#fff"), Some("nope")));
|
||||
assert!(!colors_nearly_match(
|
||||
Some("rgba(0,0,0,0.5)"),
|
||||
Some("rgba(0,0,0,0.6)")
|
||||
));
|
||||
assert!(colors_nearly_match(
|
||||
Some("rgba(0,0,0,0.5)"),
|
||||
Some("rgba(0,0,0,0.52)")
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_radial_gradient_stops_cases() {
|
||||
assert_eq!(parse_radial_gradient_stops(None), None);
|
||||
assert_eq!(
|
||||
parse_radial_gradient_stops(Some("linear-gradient(red, blue)")),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
parse_radial_gradient_stops(Some(
|
||||
"repeating-radial-gradient(circle, #000 0 2px, transparent 2px 4px)"
|
||||
)),
|
||||
None
|
||||
);
|
||||
let stops = parse_radial_gradient_stops(Some(
|
||||
"radial-gradient(circle at 50% 50%, rgba(80,111,255,0.26), transparent 44%)",
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(stops.len(), 2);
|
||||
assert_eq!(stops[0].color, Some(Rgba::new(80.0, 111.0, 255.0, 0.26)));
|
||||
assert!(!stops[0].transparent);
|
||||
assert_eq!(stops[1].color, None);
|
||||
assert!(stops[1].transparent);
|
||||
assert_eq!(
|
||||
parse_radial_gradient_stops(Some("radial-gradient(#fff, #000")),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
parse_radial_gradient_stops(Some("radial-gradient(circle, #fff)")),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shadow_layer_alpha_cases() {
|
||||
assert_eq!(shadow_layer_alpha("0 0 40px rgba(0,0,0,.5)"), 0.5);
|
||||
assert_eq!(shadow_layer_alpha("0 0 40px"), 1.0);
|
||||
assert_eq!(shadow_layer_alpha("0 0 40px transparent"), 0.0);
|
||||
assert_eq!(shadow_layer_alpha("0 0 4px #00000080"), 0.5019607843137255);
|
||||
assert_eq!(shadow_layer_alpha("inset 0 1px black"), 1.0);
|
||||
assert_eq!(shadow_layer_alpha("0 0 4px currentcolor"), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shadow_max_blur_px_defaults() {
|
||||
assert_eq!(shadow_max_blur_px(None, None), 0.0);
|
||||
assert_eq!(
|
||||
shadow_max_blur_px(Some("0 0 20px rgba(0,0,0,0.05)"), None),
|
||||
20.0
|
||||
);
|
||||
assert_eq!(
|
||||
shadow_max_blur_px(Some("0 0 20px rgba(0,0,0,0.05)"), Some(0.12)),
|
||||
0.0
|
||||
);
|
||||
assert_eq!(
|
||||
shadow_max_blur_px(Some("0 1px 2px black, 0 0 30px hsl(200, 50%, 50%)"), None),
|
||||
30.0
|
||||
);
|
||||
assert_eq!(shadow_max_blur_px(Some("0px 0px 10px"), None), 10.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn css_color_alpha_cases() {
|
||||
assert_eq!(css_color_alpha(None), 0.0);
|
||||
assert_eq!(css_color_alpha(Some("transparent")), 0.0);
|
||||
assert_eq!(css_color_alpha(Some("rgba(0,0,0,0.5)")), 0.5);
|
||||
assert_eq!(css_color_alpha(Some("#fff")), 1.0);
|
||||
assert_eq!(css_color_alpha(Some("garbage")), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn border_from_style_cases() {
|
||||
let s = style(&[
|
||||
("borderTopWidth", "1px"),
|
||||
("borderRightWidth", "0px"),
|
||||
("borderBottomWidth", "abc"),
|
||||
("borderTopColor", "red"),
|
||||
]);
|
||||
assert_eq!(border_widths_from_style(&s), [1.0, 0.0, 0.0, 0.0]);
|
||||
assert_eq!(
|
||||
border_colors_from_style(&s),
|
||||
[
|
||||
"red".to_string(),
|
||||
String::new(),
|
||||
String::new(),
|
||||
String::new()
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn positioned_style_implies_escape_cases() {
|
||||
assert!(positioned_style_implies_escape(&style(&[("top", "-10px")])));
|
||||
assert!(positioned_style_implies_escape(&style(&[("left", "100%")])));
|
||||
assert!(positioned_style_implies_escape(&style(&[(
|
||||
"inset",
|
||||
"auto calc(100% + 4px)"
|
||||
)])));
|
||||
assert!(!positioned_style_implies_escape(&style(&[("top", "10px")])));
|
||||
assert!(!positioned_style_implies_escape(&style(&[("left", "50%")])));
|
||||
assert!(!positioned_style_implies_escape(&style(&[("left", "")])));
|
||||
assert!(!positioned_style_implies_escape(&style(&[])));
|
||||
assert!(!positioned_style_implies_escape(&style(&[(
|
||||
"left",
|
||||
"calc(50%-1px)"
|
||||
)])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metric_length_cases() {
|
||||
assert_eq!(metric_length_px(LengthInput::Number(3.5), 16.0), Some(3.5));
|
||||
assert_eq!(metric_length_px(LengthInput::Number(f64::NAN), 16.0), None);
|
||||
assert_eq!(
|
||||
metric_length_px(LengthInput::Number(f64::INFINITY), 16.0),
|
||||
None
|
||||
);
|
||||
assert_eq!(metric_length_px(LengthInput::Text("2em"), 10.0), Some(20.0));
|
||||
assert_eq!(metric_length_px(LengthInput::Text("auto"), 10.0), None);
|
||||
assert_eq!(metric_length_px(LengthInput::Missing, 10.0), None);
|
||||
assert_eq!(
|
||||
first_metric_length_px(
|
||||
16.0,
|
||||
&[
|
||||
LengthInput::Missing,
|
||||
LengthInput::Text("auto"),
|
||||
LengthInput::Text("1px"),
|
||||
LengthInput::Number(9.0)
|
||||
]
|
||||
),
|
||||
Some(1.0)
|
||||
);
|
||||
assert_eq!(first_metric_length_px(16.0, &[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_box_shorthand_cases() {
|
||||
assert_eq!(expand_box_shorthand(&["a"]), vec!["a", "a", "a", "a"]);
|
||||
assert_eq!(expand_box_shorthand(&["a", "b"]), vec!["a", "b", "a", "b"]);
|
||||
assert_eq!(
|
||||
expand_box_shorthand(&["a", "b", "c"]),
|
||||
vec!["a", "b", "c", "b"]
|
||||
);
|
||||
assert_eq!(
|
||||
expand_box_shorthand(&["a", "b", "c", "d", "e"]),
|
||||
vec!["a", "b", "c", "d"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clipped_by_inset_cases() {
|
||||
assert!(clipped_by_inset(Some("inset(50%)")));
|
||||
assert!(clipped_by_inset(Some("inset(0% 50% 0% 50%)")));
|
||||
assert!(clipped_by_inset(Some("inset(50% 0%)")));
|
||||
assert!(clipped_by_inset(Some("INSET(0% 50% 0% 50% round 4px)")));
|
||||
assert!(clipped_by_inset(Some("inset(49.5% 0% 50.5%)")));
|
||||
// Every value must be a percentage: a unitless 0 fails the whole gate.
|
||||
assert!(!clipped_by_inset(Some("inset(100% 0 0 0)")));
|
||||
assert!(!clipped_by_inset(Some("inset(50% 0)")));
|
||||
assert!(!clipped_by_inset(Some("inset(10% 20%)")));
|
||||
assert!(!clipped_by_inset(Some("inset(50% 0% 49%)")));
|
||||
assert!(!clipped_by_inset(Some("inset(50px)")));
|
||||
assert!(!clipped_by_inset(Some("inset()")));
|
||||
assert!(!clipped_by_inset(Some("circle(0)")));
|
||||
assert!(!clipped_by_inset(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clipped_by_rect_cases() {
|
||||
assert!(clipped_by_rect(Some("rect(0 0 0 0)")));
|
||||
assert!(clipped_by_rect(Some("rect(0, 0, 0, 0)")));
|
||||
assert!(clipped_by_rect(Some("rect(1px, 1px, 1px, 1px)")));
|
||||
assert!(!clipped_by_rect(Some("rect(0 10px 10px 0)")));
|
||||
assert!(!clipped_by_rect(Some("rect(0 auto auto 0)")));
|
||||
assert!(!clipped_by_rect(Some("rect(0 0 0)")));
|
||||
assert!(!clipped_by_rect(Some("auto")));
|
||||
assert!(!clipped_by_rect(None));
|
||||
assert!(clipped_by_rect(Some("rect(0 1em 0 2em)")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_screen_reader_only_text_style_cases() {
|
||||
assert!(!is_screen_reader_only_text_style(
|
||||
None,
|
||||
&SrOnlyMetrics::default()
|
||||
));
|
||||
let sr = style(&[
|
||||
("position", "absolute"),
|
||||
("width", "1px"),
|
||||
("height", "1px"),
|
||||
("overflow", "hidden"),
|
||||
]);
|
||||
assert!(is_screen_reader_only_text_style(
|
||||
Some(&sr),
|
||||
&SrOnlyMetrics::default()
|
||||
));
|
||||
let sr_no_clip = style(&[
|
||||
("position", "absolute"),
|
||||
("width", "1px"),
|
||||
("height", "1px"),
|
||||
]);
|
||||
assert!(!is_screen_reader_only_text_style(
|
||||
Some(&sr_no_clip),
|
||||
&SrOnlyMetrics::default()
|
||||
));
|
||||
let sr_clip = style(&[("clip", "rect(0 0 0 0)")]);
|
||||
assert!(is_screen_reader_only_text_style(
|
||||
Some(&sr_clip),
|
||||
&SrOnlyMetrics::default()
|
||||
));
|
||||
let sr_clip_path = style(&[("webkitClipPath", "inset(50%)")]);
|
||||
assert!(is_screen_reader_only_text_style(
|
||||
Some(&sr_clip_path),
|
||||
&SrOnlyMetrics::default()
|
||||
));
|
||||
let big = style(&[
|
||||
("position", "absolute"),
|
||||
("width", "100px"),
|
||||
("height", "1px"),
|
||||
("overflow", "hidden"),
|
||||
]);
|
||||
assert!(!is_screen_reader_only_text_style(
|
||||
Some(&big),
|
||||
&SrOnlyMetrics::default()
|
||||
));
|
||||
// Metrics win over the style widths.
|
||||
assert!(is_screen_reader_only_text_style(
|
||||
Some(&big),
|
||||
&SrOnlyMetrics {
|
||||
width: Some(1.0),
|
||||
height: Some(1.0),
|
||||
..Default::default()
|
||||
}
|
||||
));
|
||||
// A 0 font size falls back to 16 for em math.
|
||||
let em = style(&[
|
||||
("position", "absolute"),
|
||||
("fontSize", "0px"),
|
||||
("width", "0.1em"),
|
||||
("height", "0.1em"),
|
||||
("overflowY", "clip"),
|
||||
]);
|
||||
assert!(is_screen_reader_only_text_style(
|
||||
Some(&em),
|
||||
&SrOnlyMetrics::default()
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cream_from_class_list_cases() {
|
||||
assert_eq!(cream_from_class_list(None), None);
|
||||
assert_eq!(cream_from_class_list(Some("")), None);
|
||||
assert_eq!(
|
||||
cream_from_class_list(Some("min-h-screen bg-amber-50 text-stone-900")),
|
||||
Some("bg-amber-50".to_string())
|
||||
);
|
||||
assert_eq!(cream_from_class_list(Some("bg-stone-50")), None);
|
||||
assert_eq!(
|
||||
cream_from_class_list(Some("p-4 bg-[#f5f0e6]")),
|
||||
Some("bg-[#f5f0e6]".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
cream_from_class_list(Some("bg-[rgb(245_240_230)]")),
|
||||
Some("bg-[rgb(245_240_230)]".to_string())
|
||||
);
|
||||
assert_eq!(cream_from_class_list(Some("bg-[#ffffff]")), None);
|
||||
assert_eq!(cream_from_class_list(Some("bg-amber-500")), None);
|
||||
assert_eq!(
|
||||
cream_from_class_list(Some("bg-[#ffffff] bg-orange-50")),
|
||||
Some("bg-orange-50".to_string())
|
||||
);
|
||||
assert_eq!(cream_from_class_list(Some("xbg-amber-50")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_opaque_decorated_box_cases() {
|
||||
assert!(!is_opaque_decorated_box(None));
|
||||
assert!(is_opaque_decorated_box(Some(&style(&[(
|
||||
"backgroundColor",
|
||||
"rgb(255, 255, 255)"
|
||||
)]))));
|
||||
assert!(!is_opaque_decorated_box(Some(&style(&[(
|
||||
"backgroundColor",
|
||||
"rgba(255, 255, 255, 0.5)"
|
||||
)]))));
|
||||
assert!(is_opaque_decorated_box(Some(&style(&[
|
||||
("borderTopWidth", "1px"),
|
||||
("borderTopColor", "rgb(0, 0, 0)"),
|
||||
("borderBottomWidth", "1px"),
|
||||
("borderBottomColor", "rgb(0, 0, 0)"),
|
||||
]))));
|
||||
assert!(!is_opaque_decorated_box(Some(&style(&[
|
||||
("borderTopWidth", "1px"),
|
||||
("borderTopColor", "rgb(0, 0, 0)"),
|
||||
("borderBottomWidth", "0px"),
|
||||
("borderBottomColor", "rgb(0, 0, 0)"),
|
||||
]))));
|
||||
assert!(!is_opaque_decorated_box(Some(&style(&[
|
||||
("borderTopWidth", "1px"),
|
||||
("borderTopColor", "rgba(0, 0, 0, 0.2)"),
|
||||
("borderBottomWidth", "1px"),
|
||||
("borderBottomColor", "rgba(0, 0, 0, 0.2)"),
|
||||
]))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
//! Port of `cli/engine/rules/checks.mjs`, split by concern so parallel work
|
||||
//! does not collide. Each module holds the rule half of its concern: the
|
||||
//! `check_*` and `scan_*` functions and the heuristics behind them. The
|
||||
//! shared half (the plain-data inputs and outputs, the CSS and text
|
||||
//! utilities, the selector and tag lists) lives in `impeccable_foundation`
|
||||
//! and is re-exported at the top of each module, so `checks::rules::RuleHit`,
|
||||
//! `checks::measures::StyleMap` and friends keep resolving here.
|
||||
//!
|
||||
//! - `rules`: Section 3 pure element checks (checkBorders, checkColors,
|
||||
//! checkHoverContrast, checkIconTile, checkItalicSerif, checkHeroEyebrow,
|
||||
//! checkKickerAboveHeading, checkMotion, checkGlow) and their heuristics
|
||||
//! (isCardLikeFromProps, resolveSerif, isAccentColor,
|
||||
//! resolveHeroHeadingSizePx). Open: `impeccable_foundation::rules::types`.
|
||||
//! - `css_scan`: CSS-text scanners (cssTextHasDarkRootBg,
|
||||
//! scanCssTextForGlow/GridBackground/RadialHalo/PseudoStripe/InsetStripe/
|
||||
//! Marquee/PulsingDot/OrganicClipPath/BuriedRaster, isRoundDotRadius).
|
||||
//! Open: `impeccable_foundation::css::scan`.
|
||||
//! - `html_patterns`: scanHtmlForShapeAssembledIllustration,
|
||||
//! buildHtmlPatternCorpora, checkHtmlPatterns. Open (the corpora type):
|
||||
//! `impeccable_foundation::rules::html_patterns`.
|
||||
//! - `measures`: the Section 4-6 gates that take plain data:
|
||||
//! checkRadialSpotlight, checkOversizedH1, checkGptThinBorderWideShadow,
|
||||
//! checkContentHiddenAtRest, isCreamColor, creamFromClassList,
|
||||
//! positionedStyleImpliesEscape, isOpaqueDecoratedBox. Open (value parsing,
|
||||
//! lengths, alphas, shadows, the style traits and the input structs):
|
||||
//! `impeccable_foundation::css::measures`.
|
||||
//! - `text_rules`: the kicker / numbered-label / em-dash / repeated-text
|
||||
//! gates: isKickerCandidate, isNumberedSectionLabelCandidate,
|
||||
//! checkNumberedSectionLabels, checkEmDashOveruse, isRepeatedTextContainer.
|
||||
//! Open (selector and tag lists, thresholds, the two text parsers):
|
||||
//! `impeccable_foundation::rules::text`.
|
||||
//!
|
||||
//! Element/document adapters (`checkElement*`, `*DOM`, `*FromDoc`) are NOT in
|
||||
//! core: the static ones live in the `html` crate against its DOM model, the
|
||||
//! browser ones live in `crate::browser` against the probe trait.
|
||||
//!
|
||||
//! `vectors_a` (rules, css_scan, html_patterns) and `vectors_b` (measures,
|
||||
//! text_rules) hold this crate's vector-replay dispatch arms for
|
||||
//! `crate::vectors`; foundation's own arms are dispatched by
|
||||
//! `impeccable_foundation::vectors`.
|
||||
|
||||
pub mod css_scan;
|
||||
pub mod html_patterns;
|
||||
pub mod measures;
|
||||
pub mod rules;
|
||||
pub mod text_rules;
|
||||
|
||||
#[cfg(feature = "vectors")]
|
||||
pub mod vectors_a;
|
||||
#[cfg(feature = "vectors")]
|
||||
pub mod vectors_b;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,451 @@
|
||||
//! Port of cli/engine/rules/checks.mjs (see checks/mod.rs for the split):
|
||||
//! the pure parts of the kicker / numbered-label / em-dash / repeated-text
|
||||
//! rules, plus the tag sets and selectors their element adapters (in the
|
||||
//! `html` crate and the browser bundle) share.
|
||||
|
||||
use crate::checks::measures::{Finding, StyleMap};
|
||||
use crate::color;
|
||||
|
||||
use crate::js::{self, ci, parse_float, parse_int, string_to_number, WS};
|
||||
|
||||
use crate::js_ext_b::{num_truthy, same_value_zero, utf16_len};
|
||||
use once_cell::sync::Lazy;
|
||||
use regex::Regex;
|
||||
|
||||
/// The selector lists, thresholds and text parsers these checks share are
|
||||
/// open; re-exported so `checks::text_rules` stays one path.
|
||||
pub use impeccable_foundation::rules::text::*;
|
||||
|
||||
macro_rules! re {
|
||||
($name:ident, $pat:expr) => {
|
||||
static $name: Lazy<Regex> = Lazy::new(|| Regex::new(&$pat).expect(stringify!($name)));
|
||||
};
|
||||
}
|
||||
|
||||
/// JS `\d` is ASCII only.
|
||||
const D: &str = "[0-9]";
|
||||
|
||||
/// JS: checks.mjs#KICKER_META_TEXT_RE (`/[·•|]|\s[\/›»>]\s|\b(19|20)\d{2}\b/`).
|
||||
pub static KICKER_META_TEXT_RE: Lazy<Regex> = Lazy::new(|| {
|
||||
Regex::new(&format!(
|
||||
r"[·•|]|{ws}[/›»>]{ws}|(?-u:\b)(19|20){d}{{2}}(?-u:\b)",
|
||||
ws = WS,
|
||||
d = D
|
||||
))
|
||||
.expect("KICKER_META_TEXT_RE")
|
||||
});
|
||||
|
||||
/// JS: checks.mjs#KICKER_DOC_NUMBERING_RE (JS `/i`).
|
||||
pub static KICKER_DOC_NUMBERING_RE: Lazy<Regex> = Lazy::new(|| {
|
||||
let words = [
|
||||
"section", "article", "clause", "appendix", "exhibit", "schedule", "chapter", "part",
|
||||
"rule", "title",
|
||||
]
|
||||
.iter()
|
||||
.map(|w| ci(w))
|
||||
.collect::<Vec<_>>()
|
||||
.join("|");
|
||||
let numbers = [
|
||||
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven",
|
||||
"twelve",
|
||||
]
|
||||
.iter()
|
||||
.map(|w| ci(w))
|
||||
.collect::<Vec<_>>()
|
||||
.join("|");
|
||||
Regex::new(&format!(
|
||||
r"^(§|{d}+(\.{d}+)+(?-u:\b)|({words}){ws}+([0-9ivxlcIVXLC]+(?-u:\b)|{numbers})(?-u:\b))",
|
||||
d = D,
|
||||
ws = WS,
|
||||
words = words,
|
||||
numbers = numbers
|
||||
))
|
||||
.expect("KICKER_DOC_NUMBERING_RE")
|
||||
});
|
||||
|
||||
// ─── Group-A helpers duplicated until rules.rs lands ────────────────────────
|
||||
|
||||
/// JS: checks.mjs#isCardLikeFromProps.
|
||||
// TODO(dedupe): use rules::is_card_like_from_props
|
||||
fn is_card_like_from_props(
|
||||
has_shadow: bool,
|
||||
has_border: bool,
|
||||
has_radius: bool,
|
||||
has_bg: bool,
|
||||
) -> bool {
|
||||
if !has_shadow && !has_border {
|
||||
return false;
|
||||
}
|
||||
has_radius || has_bg
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#isAccentColor. Whether a CSS color has visible chroma.
|
||||
// TODO(dedupe): use rules::is_accent_color
|
||||
fn is_accent_color(css_color: &str) -> bool {
|
||||
re!(
|
||||
RGB_STRICT,
|
||||
format!(
|
||||
r"rgba?\({ws}*({d}+){ws}*,{ws}*({d}+){ws}*,{ws}*({d}+)",
|
||||
ws = WS,
|
||||
d = D
|
||||
)
|
||||
);
|
||||
re!(HEX_RE, r"^#([0-9a-fA-F]{3,8})(?-u:\b)");
|
||||
re!(OKLCH_START, format!(r"^{}\(", ci("oklch")));
|
||||
re!(NUM_RE, format!(r"{d}*\.{d}+|{d}+", d = D));
|
||||
re!(
|
||||
HSL_RE,
|
||||
format!(
|
||||
r"{hsl}[aA]?\({ws}*[0-9.]+{ws}*,{ws}*([0-9.]+)%",
|
||||
hsl = ci("hsl"),
|
||||
ws = WS
|
||||
)
|
||||
);
|
||||
if css_color.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let s = js::trim(css_color);
|
||||
if let Some(m) = RGB_STRICT.captures(s) {
|
||||
let r = string_to_number(&m[1]);
|
||||
let g = string_to_number(&m[2]);
|
||||
let b = string_to_number(&m[3]);
|
||||
return js::math_max3(r, g, b) - js::math_min3(r, g, b) >= 40.0;
|
||||
}
|
||||
if let Some(m) = HEX_RE.captures(s) {
|
||||
let mut h = m[1].to_string();
|
||||
if h.len() == 3 || h.len() == 4 {
|
||||
let doubled: String = h.chars().flat_map(|c| [c, c]).collect();
|
||||
h = doubled.chars().take(6).collect();
|
||||
} else {
|
||||
h = h.chars().take(6).collect();
|
||||
}
|
||||
if h.len() == 6 {
|
||||
let r = parse_int(&h[0..2], 16);
|
||||
let g = parse_int(&h[2..4], 16);
|
||||
let b = parse_int(&h[4..6], 16);
|
||||
return js::math_max3(r, g, b) - js::math_min3(r, g, b) >= 40.0;
|
||||
}
|
||||
}
|
||||
if OKLCH_START.is_match(s) {
|
||||
let nums: Vec<&str> = NUM_RE.find_iter(s).map(|m| m.as_str()).collect();
|
||||
if nums.len() >= 2 {
|
||||
let c = parse_float(nums[1]);
|
||||
return !c.is_nan() && c >= 0.05;
|
||||
}
|
||||
}
|
||||
if let Some(m) = HSL_RE.captures(s) {
|
||||
let sat = parse_float(&m[1]);
|
||||
return !sat.is_nan() && sat >= 20.0;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#isKickerCandidate.
|
||||
pub fn is_kicker_candidate(o: &KickerCandidateInput) -> bool {
|
||||
re!(SLASH_PATH_RE, r"^/[0-9A-Za-z_-]+");
|
||||
re!(
|
||||
STEP_RE,
|
||||
format!(r"^{}{ws}*{d}+", ci("step"), ws = WS, d = D)
|
||||
);
|
||||
re!(TWO_DIGITS_RE, format!(r"^{d}{{1,2}}$", d = D));
|
||||
if !num_truthy(o.heading_level) || o.heading_level > 4.0 {
|
||||
return false;
|
||||
}
|
||||
if o.heading_text.is_empty() || utf16_len(o.heading_text) < 3 {
|
||||
return false;
|
||||
}
|
||||
let unquoted = strip_edge_quotes(o.heading_text);
|
||||
if SLASH_PATH_RE.is_match(js::trim(&unquoted)) {
|
||||
return false;
|
||||
}
|
||||
if !(o.heading_font_size >= 20.0) {
|
||||
return false;
|
||||
}
|
||||
if o.kicker_tag.is_empty() || HEADING_TAGS.contains(&o.kicker_tag) {
|
||||
return false;
|
||||
}
|
||||
if !["p", "span", "div", "small"].contains(&o.kicker_tag) {
|
||||
return false;
|
||||
}
|
||||
let kicker_len = utf16_len(o.kicker_text);
|
||||
if o.kicker_text.is_empty() || kicker_len < 2 || kicker_len > 34 {
|
||||
return false;
|
||||
}
|
||||
if STEP_RE.is_match(o.kicker_text) || TWO_DIGITS_RE.is_match(o.kicker_text) {
|
||||
return false;
|
||||
}
|
||||
if KICKER_META_TEXT_RE.is_match(o.kicker_text) {
|
||||
return false;
|
||||
}
|
||||
if KICKER_DOC_NUMBERING_RE.is_match(o.kicker_text) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let is_small_caps = o.kicker_font_variant.contains("small-caps");
|
||||
let has_upper = o.kicker_text.chars().any(|c| c.is_ascii_uppercase());
|
||||
let has_lower = o.kicker_text.chars().any(|c| c.is_ascii_lowercase());
|
||||
let is_uppercased =
|
||||
o.kicker_text_transform == "uppercase" || (has_upper && !has_lower) || is_small_caps;
|
||||
if !is_uppercased {
|
||||
return false;
|
||||
}
|
||||
if !(o.kicker_font_size > 0.0 && o.kicker_font_size <= 14.0) {
|
||||
return false;
|
||||
}
|
||||
let min_tracked_spacing = o.kicker_font_size * 0.06;
|
||||
if !(o.kicker_letter_spacing >= min_tracked_spacing) {
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#isNumberedSectionLabelCandidate.
|
||||
pub fn is_numbered_section_label_candidate(o: &NumberedLabelCandidateInput) -> bool {
|
||||
re!(MONO_RE, ci("mono"));
|
||||
if !["h2", "h3", "h4"].contains(&o.heading_tag) {
|
||||
return false;
|
||||
}
|
||||
if o.heading_text.is_empty() || utf16_len(o.heading_text) < 3 {
|
||||
return false;
|
||||
}
|
||||
if o.label_tag.is_empty() || !NUMBERED_LABEL_TAGS.contains(&o.label_tag) {
|
||||
return false;
|
||||
}
|
||||
if o.label_index.is_none() || o.label_text.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if !(o.label_font_size > 0.0 && o.label_font_size <= 13.0) {
|
||||
return false;
|
||||
}
|
||||
if o.heading_font_size > 0.0 && o.heading_font_size < o.label_font_size * 1.3 {
|
||||
return false;
|
||||
}
|
||||
let weight_n = string_to_number(o.label_font_weight);
|
||||
let weight = if num_truthy(weight_n) {
|
||||
weight_n
|
||||
} else {
|
||||
400.0
|
||||
};
|
||||
let spacing = if num_truthy(o.label_letter_spacing) {
|
||||
o.label_letter_spacing
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
MONO_RE.is_match(o.label_font_family)
|
||||
|| weight >= 600.0
|
||||
|| spacing >= 0.5
|
||||
|| o.label_text_transform == "uppercase"
|
||||
|| is_accent_color(o.label_color)
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#checkNumberedSectionLabels (`min_count` default 2).
|
||||
pub fn check_numbered_section_labels(
|
||||
candidates: &[NumberedLabelCandidate],
|
||||
min_count: Option<f64>,
|
||||
) -> Vec<Finding> {
|
||||
let min_count = min_count.unwrap_or(2.0);
|
||||
if (candidates.len() as f64) < min_count {
|
||||
return vec![];
|
||||
}
|
||||
let mut distinct: Vec<f64> = Vec::new();
|
||||
for c in candidates {
|
||||
if !distinct.iter().any(|d| same_value_zero(*d, c.index)) {
|
||||
distinct.push(c.index);
|
||||
}
|
||||
}
|
||||
if distinct.len() < 2 {
|
||||
return vec![];
|
||||
}
|
||||
candidates
|
||||
.iter()
|
||||
.map(|c| {
|
||||
Finding::new(
|
||||
"numbered-section-labels",
|
||||
format!(
|
||||
"tiny numbered label \"{}\" beside {} \"{}\" ({} on page)",
|
||||
c.label_text,
|
||||
c.heading_tag,
|
||||
c.heading_text,
|
||||
candidates.len()
|
||||
),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// JS `/[—]|--(?=\S)/g` match count over `body`.
|
||||
fn count_em_dashes(body: &str) -> usize {
|
||||
let chars: Vec<char> = body.chars().collect();
|
||||
let mut count = 0usize;
|
||||
let mut i = 0usize;
|
||||
while i < chars.len() {
|
||||
if chars[i] == '—' {
|
||||
count += 1;
|
||||
i += 1;
|
||||
} else if chars[i] == '-'
|
||||
&& i + 2 < chars.len()
|
||||
&& chars[i + 1] == '-'
|
||||
&& !js::is_js_whitespace(chars[i + 2])
|
||||
{
|
||||
count += 1;
|
||||
i += 2;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
/// JS: checks.mjs#checkEmDashOveruse. Two gates (absolute floor + density)
|
||||
/// over already-rendered text. `None` for a non-string input.
|
||||
pub fn check_em_dash_overuse(text: Option<&str>) -> Vec<Finding> {
|
||||
re!(WS_RE, format!("{}+", WS));
|
||||
let body: String = match text {
|
||||
Some(t) => WS_RE.replace_all(t, " ").into_owned(),
|
||||
None => String::new(),
|
||||
};
|
||||
let count = count_em_dashes(&body);
|
||||
if count < EM_DASH_FLOOR {
|
||||
return vec![];
|
||||
}
|
||||
if utf16_len(&body) > count * EM_DASH_CHARS_PER_DASH {
|
||||
return vec![];
|
||||
}
|
||||
vec![Finding::new(
|
||||
"em-dash-overuse",
|
||||
format!("{} em-dashes in body text", count),
|
||||
)]
|
||||
}
|
||||
|
||||
// ─── Repeated container text ────────────────────────────────────────────────
|
||||
|
||||
/// JS: checks.mjs#isRepeatedTextContainer. A container worth attributing
|
||||
/// text to: visibly bounded and surface-like.
|
||||
pub fn is_repeated_text_container(style: Option<&dyn StyleMap>) -> bool {
|
||||
let Some(style) = style else { return false };
|
||||
let box_shadow = style.prop("boxShadow");
|
||||
let has_shadow = matches!(box_shadow.as_deref(), Some(v) if v != "none" && !v.is_empty());
|
||||
let border_sides = ["Top", "Right", "Bottom", "Left"]
|
||||
.iter()
|
||||
.filter(|side| {
|
||||
let w = parse_float(
|
||||
&style
|
||||
.prop(&format!("border{}Width", side))
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
let w = if num_truthy(w) { w } else { 0.0 };
|
||||
w >= 1.0
|
||||
})
|
||||
.count();
|
||||
let has_border = border_sides >= 3;
|
||||
let radius = parse_float(&style.prop("borderRadius").unwrap_or_default());
|
||||
let has_radius = num_truthy(radius) && radius > 0.0;
|
||||
let bgc = style.prop("backgroundColor");
|
||||
let bg = color::parse_rgb(bgc.as_deref()).or_else(|| color::parse_any_color(bgc.as_deref()));
|
||||
let has_bg = matches!(bg, Some(c) if c.alpha_or_one() > 0.1);
|
||||
is_card_like_from_props(has_shadow, has_border, has_radius, has_bg)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn style(pairs: &[(&str, &str)]) -> HashMap<String, String> {
|
||||
pairs
|
||||
.iter()
|
||||
.map(|(k, v)| (k.to_string(), v.to_string()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
// Expected values below were produced by running the JS functions in Node.
|
||||
|
||||
#[test]
|
||||
fn is_accent_color_cases() {
|
||||
assert!(!is_accent_color(""));
|
||||
assert!(is_accent_color("rgb(180, 83, 9)"));
|
||||
assert!(!is_accent_color("rgb(120, 120, 130)"));
|
||||
assert!(is_accent_color("#f00"));
|
||||
assert!(!is_accent_color("#888"));
|
||||
assert!(is_accent_color("#ff000080"));
|
||||
assert!(!is_accent_color("#12345"));
|
||||
assert!(is_accent_color("oklch(43%.15 34)"));
|
||||
assert!(!is_accent_color("oklch(0.5 0.01 200)"));
|
||||
assert!(is_accent_color("hsl(200, 50%, 50%)"));
|
||||
assert!(!is_accent_color("hsla(200, 10%, 50%, 0.5)"));
|
||||
assert!(!is_accent_color("var(--x)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strip_edge_quotes_cases() {
|
||||
assert_eq!(strip_edge_quotes("\"a\""), "a");
|
||||
assert_eq!(strip_edge_quotes("\""), "");
|
||||
assert_eq!(strip_edge_quotes("\"\""), "");
|
||||
assert_eq!(strip_edge_quotes("a\"b"), "a\"b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn count_em_dashes_cases() {
|
||||
assert_eq!(count_em_dashes("a — b — c"), 2);
|
||||
assert_eq!(count_em_dashes("a--b"), 1);
|
||||
assert_eq!(count_em_dashes("a-- b"), 0);
|
||||
assert_eq!(count_em_dashes("----x"), 2);
|
||||
assert_eq!(count_em_dashes("---x"), 1);
|
||||
assert_eq!(count_em_dashes("--"), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_em_dash_overuse_non_string() {
|
||||
assert!(check_em_dash_overuse(None).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_repeated_text_container_cases() {
|
||||
assert!(!is_repeated_text_container(None));
|
||||
assert!(is_repeated_text_container(Some(&style(&[
|
||||
("boxShadow", "0 1px 2px rgba(0,0,0,0.2)"),
|
||||
("borderRadius", "8px"),
|
||||
]))));
|
||||
assert!(!is_repeated_text_container(Some(&style(&[
|
||||
("boxShadow", "none"),
|
||||
("borderRadius", "8px"),
|
||||
]))));
|
||||
assert!(is_repeated_text_container(Some(&style(&[
|
||||
("borderTopWidth", "1px"),
|
||||
("borderRightWidth", "1px"),
|
||||
("borderBottomWidth", "1px"),
|
||||
("backgroundColor", "rgb(255, 255, 255)"),
|
||||
]))));
|
||||
assert!(!is_repeated_text_container(Some(&style(&[
|
||||
("borderTopWidth", "1px"),
|
||||
("borderRightWidth", "1px"),
|
||||
("backgroundColor", "rgb(255, 255, 255)"),
|
||||
]))));
|
||||
assert!(!is_repeated_text_container(Some(&style(&[
|
||||
("borderTopWidth", "1px"),
|
||||
("borderRightWidth", "1px"),
|
||||
("borderBottomWidth", "1px"),
|
||||
("backgroundColor", "rgba(255, 255, 255, 0.05)"),
|
||||
]))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kicker_regex_cases() {
|
||||
assert!(KICKER_META_TEXT_RE.is_match("News · 2024"));
|
||||
assert!(KICKER_META_TEXT_RE.is_match("Docs / Guides"));
|
||||
assert!(KICKER_META_TEXT_RE.is_match("Since 1999"));
|
||||
assert!(!KICKER_META_TEXT_RE.is_match("Our story"));
|
||||
assert!(!KICKER_META_TEXT_RE.is_match("Docs/Guides"));
|
||||
assert!(KICKER_DOC_NUMBERING_RE.is_match("Section 4.2"));
|
||||
assert!(KICKER_DOC_NUMBERING_RE.is_match("ARTICLE IX"));
|
||||
assert!(KICKER_DOC_NUMBERING_RE.is_match("§ 12.3"));
|
||||
assert!(KICKER_DOC_NUMBERING_RE.is_match("1.2.3 Scope"));
|
||||
assert!(KICKER_DOC_NUMBERING_RE.is_match("Chapter one"));
|
||||
assert!(!KICKER_DOC_NUMBERING_RE.is_match("Section"));
|
||||
assert!(!KICKER_DOC_NUMBERING_RE.is_match("Partial"));
|
||||
assert!(!KICKER_DOC_NUMBERING_RE.is_match("12 Scope"));
|
||||
assert!(CURSOR_GLYPH_RE.is_match("▌"));
|
||||
assert!(CURSOR_GLYPH_RE.is_match("_"));
|
||||
assert!(!CURSOR_GLYPH_RE.is_match("__"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,383 @@
|
||||
//! Vector-replay dispatch for the checks of group a (`rules`,
|
||||
//! `css_scan`, `html_patterns`). `crate::vectors::call` tries the open
|
||||
//! foundation arms first, then this; returns None for functions this group
|
||||
//! does not own.
|
||||
|
||||
use crate::checks::css_scan::{self, IndexedHit, PatternFinding};
|
||||
use crate::checks::html_patterns::{self, HtmlPatternCorpora};
|
||||
use crate::checks::rules::{self, RuleHit};
|
||||
use crate::color::Rgba;
|
||||
|
||||
use crate::js_ext_a::utf16_index;
|
||||
use crate::vectors::{decode, encode, Js};
|
||||
use impeccable_foundation::vectors::checks_a::{field, opt_str, str_or_empty, to_number, truthy};
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// (module, fn) pairs this group replays; the test treats vectors for other
|
||||
/// functions as SKIP, not FAIL, so groups can land independently. The open
|
||||
/// helpers of this group are dispatched by
|
||||
/// `impeccable_foundation::vectors::checks_a`.
|
||||
pub const KNOWN: &[(&str, &[&str])] = &[(
|
||||
"rules.checks",
|
||||
&[
|
||||
"checkBorders",
|
||||
"checkColors",
|
||||
"checkHoverContrast",
|
||||
"isCardLikeFromProps",
|
||||
"checkIconTile",
|
||||
"resolveSerif",
|
||||
"checkItalicSerif",
|
||||
"isAccentColor",
|
||||
"resolveHeroHeadingSizePx",
|
||||
"checkHeroEyebrow",
|
||||
"checkKickerAboveHeading",
|
||||
"checkMotion",
|
||||
"checkGlow",
|
||||
"cssTextHasDarkRootBg",
|
||||
"scanCssTextForGlow",
|
||||
"scanCssTextForGridBackground",
|
||||
"scanCssTextForRadialHalo",
|
||||
"scanCssTextForPseudoStripe",
|
||||
"scanCssTextForInsetStripe",
|
||||
"scanCssTextForMarquee",
|
||||
"isRoundDotRadius",
|
||||
"scanCssTextForPulsingDot",
|
||||
"scanHtmlForShapeAssembledIllustration",
|
||||
"buildHtmlPatternCorpora",
|
||||
"checkHtmlPatterns",
|
||||
],
|
||||
)];
|
||||
|
||||
fn rgba(j: Option<&Js>) -> Option<Rgba> {
|
||||
match j {
|
||||
Some(Js::Obj(_)) => {
|
||||
let o = j.unwrap();
|
||||
Some(Rgba {
|
||||
r: to_number(field(o, "r")),
|
||||
g: to_number(field(o, "g")),
|
||||
b: to_number(field(o, "b")),
|
||||
a: match field(o, "a") {
|
||||
None | Some(Js::Undef) => None,
|
||||
v => Some(to_number(v)),
|
||||
},
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn hits_to_js(hits: &[RuleHit]) -> Js {
|
||||
Js::Arr(
|
||||
hits.iter()
|
||||
.map(|h| {
|
||||
Js::Obj(vec![
|
||||
("id".to_string(), Js::Str(h.id.clone())),
|
||||
("snippet".to_string(), Js::Str(h.snippet.clone())),
|
||||
])
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
fn indexed_to_js(text: &str, hits: &[IndexedHit]) -> Js {
|
||||
Js::Arr(
|
||||
hits.iter()
|
||||
.map(|h| {
|
||||
Js::Obj(vec![
|
||||
(
|
||||
"index".to_string(),
|
||||
Js::Num(utf16_index(text, h.index) as f64),
|
||||
),
|
||||
("snippet".to_string(), Js::Str(h.snippet.clone())),
|
||||
])
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
fn patterns_to_js(text: &str, findings: &[PatternFinding]) -> Js {
|
||||
Js::Arr(
|
||||
findings
|
||||
.iter()
|
||||
.map(|f| {
|
||||
let mut fields = vec![
|
||||
("id".to_string(), Js::Str(f.id.clone())),
|
||||
("snippet".to_string(), Js::Str(f.snippet.clone())),
|
||||
];
|
||||
if let Some(sel) = &f.selector {
|
||||
fields.push(("selector".to_string(), Js::Str(sel.clone())));
|
||||
}
|
||||
if let Some(idx) = f.index {
|
||||
fields.push(("index".to_string(), Js::Num(utf16_index(text, idx) as f64)));
|
||||
}
|
||||
if let Some(sev) = &f.severity {
|
||||
fields.push(("severity".to_string(), Js::Str(sev.clone())));
|
||||
}
|
||||
Js::Obj(fields)
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn call(module: &str, fn_name: &str, args: &[Value]) -> Option<Value> {
|
||||
if module != "rules.checks" {
|
||||
return None;
|
||||
}
|
||||
let a: Vec<Js> = args.iter().map(decode).collect();
|
||||
let arg = |i: usize| -> Option<&Js> {
|
||||
match a.get(i) {
|
||||
Some(Js::Undef) | None => None,
|
||||
Some(v) => Some(v),
|
||||
}
|
||||
};
|
||||
let f = |i: usize, key: &str| -> Option<&Js> { arg(i).and_then(|o| field(o, key)) };
|
||||
let result: Js = match fn_name {
|
||||
"checkBorders" => {
|
||||
let widths = rules::Sides {
|
||||
top: to_number(f(1, "Top")),
|
||||
right: to_number(f(1, "Right")),
|
||||
bottom: to_number(f(1, "Bottom")),
|
||||
left: to_number(f(1, "Left")),
|
||||
};
|
||||
let cs = [
|
||||
opt_str(f(2, "Top")),
|
||||
opt_str(f(2, "Right")),
|
||||
opt_str(f(2, "Bottom")),
|
||||
opt_str(f(2, "Left")),
|
||||
];
|
||||
let colors = rules::Sides {
|
||||
top: cs[0].as_deref(),
|
||||
right: cs[1].as_deref(),
|
||||
bottom: cs[2].as_deref(),
|
||||
left: cs[3].as_deref(),
|
||||
};
|
||||
let opts = rules::BorderOpts {
|
||||
badge_like: truthy(f(4, "badgeLike")),
|
||||
status_context: truthy(f(4, "statusContext")),
|
||||
tab_context: truthy(f(4, "tabContext")),
|
||||
};
|
||||
hits_to_js(&rules::check_borders(
|
||||
&str_or_empty(arg(0)),
|
||||
&widths,
|
||||
&colors,
|
||||
to_number(arg(3)),
|
||||
&opts,
|
||||
))
|
||||
}
|
||||
"checkColors" => {
|
||||
let stops = match f(0, "effectiveBgStops") {
|
||||
Some(Js::Arr(items)) => Some(
|
||||
items
|
||||
.iter()
|
||||
.filter_map(|i| rgba(Some(i)))
|
||||
.collect::<Vec<_>>(),
|
||||
),
|
||||
_ => None,
|
||||
};
|
||||
let opts = rules::ColorOpts {
|
||||
tag: str_or_empty(f(0, "tag")),
|
||||
text_color: rgba(f(0, "textColor")),
|
||||
bg_color: rgba(f(0, "bgColor")),
|
||||
effective_bg: rgba(f(0, "effectiveBg")),
|
||||
effective_bg_stops: stops,
|
||||
font_size: to_number(f(0, "fontSize")),
|
||||
font_weight: to_number(f(0, "fontWeight")),
|
||||
has_direct_text: truthy(f(0, "hasDirectText")),
|
||||
is_emoji_only: truthy(f(0, "isEmojiOnly")),
|
||||
bg_clip: opt_str(f(0, "bgClip")),
|
||||
bg_image: opt_str(f(0, "bgImage")),
|
||||
class_list: opt_str(f(0, "classList")),
|
||||
detector_is_browser: false,
|
||||
};
|
||||
hits_to_js(&rules::check_colors(&opts))
|
||||
}
|
||||
"checkHoverContrast" => {
|
||||
let opts = rules::HoverContrastOpts {
|
||||
tag: str_or_empty(f(0, "tag")),
|
||||
text_color: rgba(f(0, "textColor")),
|
||||
bg: rgba(f(0, "bg")),
|
||||
own_bg_alpha: match f(0, "ownBgAlpha") {
|
||||
None | Some(Js::Undef) | Some(Js::Null) => None,
|
||||
v => Some(to_number(v)),
|
||||
},
|
||||
font_size: to_number(f(0, "fontSize")),
|
||||
font_weight: to_number(f(0, "fontWeight")),
|
||||
has_direct_text: truthy(f(0, "hasDirectText")),
|
||||
is_emoji_only: truthy(f(0, "isEmojiOnly")),
|
||||
};
|
||||
hits_to_js(&rules::check_hover_contrast(&opts))
|
||||
}
|
||||
"isCardLikeFromProps" => Js::Bool(rules::is_card_like_from_props(
|
||||
truthy(arg(0)),
|
||||
truthy(arg(1)),
|
||||
truthy(arg(2)),
|
||||
truthy(arg(3)),
|
||||
)),
|
||||
"checkIconTile" => {
|
||||
let opts = rules::IconTileOpts {
|
||||
heading_tag: str_or_empty(f(0, "headingTag")),
|
||||
heading_text: opt_str(f(0, "headingText")),
|
||||
heading_top: to_number(f(0, "headingTop")),
|
||||
sibling_tag: opt_str(f(0, "siblingTag")),
|
||||
sibling_width: to_number(f(0, "siblingWidth")),
|
||||
sibling_height: to_number(f(0, "siblingHeight")),
|
||||
sibling_bottom: to_number(f(0, "siblingBottom")),
|
||||
sibling_bg_color: rgba(f(0, "siblingBgColor")),
|
||||
sibling_bg_image: opt_str(f(0, "siblingBgImage")),
|
||||
sibling_border_width: to_number(f(0, "siblingBorderWidth")),
|
||||
sibling_border_radius: to_number(f(0, "siblingBorderRadius")),
|
||||
has_icon_child: truthy(f(0, "hasIconChild")),
|
||||
icon_child_width: to_number(f(0, "iconChildWidth")),
|
||||
};
|
||||
hits_to_js(&rules::check_icon_tile(&opts))
|
||||
}
|
||||
"resolveSerif" => {
|
||||
let r = rules::resolve_serif(opt_str(arg(0)).as_deref());
|
||||
Js::Obj(vec![
|
||||
(
|
||||
"primary".to_string(),
|
||||
r.primary.map(Js::Str).unwrap_or(Js::Null),
|
||||
),
|
||||
("isSerif".to_string(), Js::Bool(r.is_serif)),
|
||||
])
|
||||
}
|
||||
"checkItalicSerif" => {
|
||||
let opts = rules::ItalicSerifOpts {
|
||||
tag: str_or_empty(f(0, "tag")),
|
||||
font_style: opt_str(f(0, "fontStyle")),
|
||||
font_family: opt_str(f(0, "fontFamily")),
|
||||
font_size: to_number(f(0, "fontSize")),
|
||||
heading_text: opt_str(f(0, "headingText")),
|
||||
};
|
||||
hits_to_js(&rules::check_italic_serif(&opts))
|
||||
}
|
||||
"isAccentColor" => Js::Bool(rules::is_accent_color(&str_or_empty(arg(0)))),
|
||||
"resolveHeroHeadingSizePx" => Js::Num(rules::resolve_hero_heading_size_px(
|
||||
opt_str(arg(0)).as_deref(),
|
||||
)),
|
||||
"checkHeroEyebrow" => {
|
||||
let opts = rules::HeroEyebrowOpts {
|
||||
heading_tag: str_or_empty(f(0, "headingTag")),
|
||||
heading_text: opt_str(f(0, "headingText")),
|
||||
heading_font_size: to_number(f(0, "headingFontSize")),
|
||||
heading_in_application_context: truthy(f(0, "headingInApplicationContext")),
|
||||
sibling_tag: opt_str(f(0, "siblingTag")),
|
||||
sibling_text: opt_str(f(0, "siblingText")),
|
||||
sibling_text_transform: opt_str(f(0, "siblingTextTransform")),
|
||||
sibling_font_size: to_number(f(0, "siblingFontSize")),
|
||||
sibling_letter_spacing: to_number(f(0, "siblingLetterSpacing")),
|
||||
sibling_font_weight: opt_str(f(0, "siblingFontWeight")),
|
||||
sibling_color: opt_str(f(0, "siblingColor")),
|
||||
sibling_has_accent_dash_pseudo: truthy(f(0, "siblingHasAccentDashPseudo")),
|
||||
};
|
||||
hits_to_js(&rules::check_hero_eyebrow(&opts))
|
||||
}
|
||||
"checkKickerAboveHeading" => {
|
||||
let candidates: Vec<rules::KickerCandidate> = match f(0, "candidates") {
|
||||
Some(Js::Arr(items)) => items
|
||||
.iter()
|
||||
.map(|c| rules::KickerCandidate {
|
||||
heading_tag: opt_str(field(c, "headingTag"))
|
||||
.unwrap_or_else(|| "undefined".to_string()),
|
||||
heading_text: opt_str(field(c, "headingText"))
|
||||
.unwrap_or_else(|| "undefined".to_string()),
|
||||
kicker_text: opt_str(field(c, "kickerText"))
|
||||
.unwrap_or_else(|| "undefined".to_string()),
|
||||
})
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
hits_to_js(&rules::check_kicker_above_heading(&candidates))
|
||||
}
|
||||
"checkMotion" => {
|
||||
let opts = rules::MotionOpts {
|
||||
tag: str_or_empty(f(0, "tag")),
|
||||
transition_property: opt_str(f(0, "transitionProperty")),
|
||||
animation_name: opt_str(f(0, "animationName")),
|
||||
timing_functions: opt_str(f(0, "timingFunctions")),
|
||||
class_list: opt_str(f(0, "classList")),
|
||||
};
|
||||
hits_to_js(&rules::check_motion(&opts))
|
||||
}
|
||||
"checkGlow" => {
|
||||
let opts = rules::GlowOpts {
|
||||
box_shadow: opt_str(f(0, "boxShadow")),
|
||||
text_shadow: opt_str(f(0, "textShadow")),
|
||||
effective_bg: rgba(f(0, "effectiveBg")),
|
||||
};
|
||||
hits_to_js(&rules::check_glow(&opts))
|
||||
}
|
||||
"cssTextHasDarkRootBg" => {
|
||||
let content = str_or_empty(arg(0));
|
||||
let props = css_scan::collect_css_custom_props(&content);
|
||||
Js::Bool(css_scan::css_text_has_dark_root_bg(&content, &props))
|
||||
}
|
||||
"scanCssTextForGlow" => {
|
||||
let text = str_or_empty(arg(0));
|
||||
indexed_to_js(&text, &css_scan::scan_css_text_for_glow(&text))
|
||||
}
|
||||
"scanCssTextForGridBackground" => {
|
||||
let text = str_or_empty(arg(0));
|
||||
indexed_to_js(&text, &css_scan::scan_css_text_for_grid_background(&text))
|
||||
}
|
||||
"scanCssTextForRadialHalo" => {
|
||||
let text = str_or_empty(arg(0));
|
||||
indexed_to_js(&text, &css_scan::scan_css_text_for_radial_halo(&text))
|
||||
}
|
||||
"scanCssTextForPseudoStripe" => {
|
||||
let raw = str_or_empty(arg(0));
|
||||
let out = css_scan::scan_css_text_for_pseudo_stripe(&raw);
|
||||
patterns_to_js(&raw, &out)
|
||||
}
|
||||
"scanCssTextForInsetStripe" => {
|
||||
let text = str_or_empty(arg(0));
|
||||
patterns_to_js(&text, &css_scan::scan_css_text_for_inset_stripe(&text))
|
||||
}
|
||||
"scanCssTextForMarquee" => {
|
||||
let content = str_or_empty(arg(0));
|
||||
let markup = opt_str(arg(1));
|
||||
patterns_to_js(
|
||||
&content,
|
||||
&css_scan::scan_css_text_for_marquee(&content, markup.as_deref()),
|
||||
)
|
||||
}
|
||||
"isRoundDotRadius" => Js::Bool(css_scan::is_round_dot_radius(
|
||||
&str_or_empty(arg(0)),
|
||||
to_number(arg(1)),
|
||||
to_number(arg(2)),
|
||||
)),
|
||||
"scanCssTextForPulsingDot" => {
|
||||
let content = str_or_empty(arg(0));
|
||||
let markup = opt_str(arg(1));
|
||||
patterns_to_js(
|
||||
&content,
|
||||
&css_scan::scan_css_text_for_pulsing_dot(&content, markup.as_deref()),
|
||||
)
|
||||
}
|
||||
"scanHtmlForShapeAssembledIllustration" => hits_to_js(
|
||||
&html_patterns::scan_html_for_shape_assembled_illustration(&str_or_empty(arg(0))),
|
||||
),
|
||||
"buildHtmlPatternCorpora" => {
|
||||
let c = html_patterns::build_html_pattern_corpora(&str_or_empty(arg(0)));
|
||||
Js::Obj(vec![
|
||||
("styleText".to_string(), Js::Str(c.style_text)),
|
||||
("classText".to_string(), Js::Str(c.class_text)),
|
||||
])
|
||||
}
|
||||
"checkHtmlPatterns" => {
|
||||
let html = str_or_empty(arg(0));
|
||||
let corpora = arg(1).map(|c| HtmlPatternCorpora {
|
||||
style_text: str_or_empty(field(c, "styleText")),
|
||||
class_text: str_or_empty(field(c, "classText")),
|
||||
});
|
||||
let effective = corpora
|
||||
.clone()
|
||||
.unwrap_or_else(|| html_patterns::build_html_pattern_corpora(&html));
|
||||
let out = html_patterns::check_html_patterns(&html, corpora.as_ref());
|
||||
patterns_to_js(&effective.style_text, &out)
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
Some(encode(&result))
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
//! Vector-replay dispatch for the checks of group b (`measures`,
|
||||
//! `text_rules`). `crate::vectors::call` tries the foundation arms
|
||||
//! first, then this; returns None for functions this group does not own.
|
||||
|
||||
use crate::checks::measures::{self, Finding};
|
||||
use crate::checks::text_rules;
|
||||
use crate::color::Rgba;
|
||||
use crate::js;
|
||||
use crate::vectors::{decode, encode, Js};
|
||||
|
||||
use impeccable_foundation::vectors::checks_b::{
|
||||
field, num_field, opt_str, str_field, str_field_or_empty, to_number,
|
||||
};
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// (module, fn) pairs this group replays; the test treats vectors for other
|
||||
/// functions as SKIP, not FAIL, so groups can land independently. The open
|
||||
/// helpers of this group are dispatched by
|
||||
/// `impeccable_foundation::vectors::checks_b`.
|
||||
pub const KNOWN: &[(&str, &[&str])] = &[(
|
||||
"rules.checks",
|
||||
&[
|
||||
"checkRadialSpotlight",
|
||||
"checkOversizedH1",
|
||||
"checkGptThinBorderWideShadow",
|
||||
"checkContentHiddenAtRest",
|
||||
"isCreamColor",
|
||||
"isKickerCandidate",
|
||||
"isNumberedSectionLabelCandidate",
|
||||
"checkNumberedSectionLabels",
|
||||
"checkEmDashOveruse",
|
||||
],
|
||||
)];
|
||||
|
||||
fn rgba_from(j: &Js) -> Option<Rgba> {
|
||||
match j {
|
||||
Js::Obj(_) => Some(Rgba {
|
||||
r: num_field(j, "r"),
|
||||
g: num_field(j, "g"),
|
||||
b: num_field(j, "b"),
|
||||
a: match field(j, "a") {
|
||||
None | Some(Js::Undef) => None,
|
||||
Some(v) => Some(to_number(v)),
|
||||
},
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn findings_to_js(findings: &[Finding]) -> Js {
|
||||
Js::Arr(
|
||||
findings
|
||||
.iter()
|
||||
.map(|f| {
|
||||
Js::Obj(vec![
|
||||
("id".to_string(), Js::Str(f.id.clone())),
|
||||
("snippet".to_string(), Js::Str(f.snippet.clone())),
|
||||
])
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn call(module: &str, fn_name: &str, args: &[Value]) -> Option<Value> {
|
||||
if module != "rules.checks" {
|
||||
return None;
|
||||
}
|
||||
let a: Vec<Js> = args.iter().map(decode).collect();
|
||||
let arg = |i: usize| a.get(i).cloned().unwrap_or(Js::Undef);
|
||||
let result: Js = match fn_name {
|
||||
"checkRadialSpotlight" => {
|
||||
let o = arg(0);
|
||||
let input = measures::RadialSpotlightInput {
|
||||
gradient_value: str_field(&o, "gradientValue"),
|
||||
width: num_field(&o, "width"),
|
||||
height: num_field(&o, "height"),
|
||||
label: str_field(&o, "label"),
|
||||
};
|
||||
findings_to_js(&measures::check_radial_spotlight(&input))
|
||||
}
|
||||
"checkOversizedH1" => {
|
||||
let o = arg(0);
|
||||
let rect = match field(&o, "rect") {
|
||||
Some(r @ Js::Obj(_)) => Some(measures::Rect {
|
||||
width: num_field(r, "width"),
|
||||
height: num_field(r, "height"),
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
let vp = |key: &str| match field(&o, key) {
|
||||
None | Some(Js::Undef) => 0.0,
|
||||
Some(v) => to_number(v),
|
||||
};
|
||||
let input = measures::OversizedH1Input {
|
||||
tag: str_field_or_empty(&o, "tag"),
|
||||
font_size: num_field(&o, "fontSize"),
|
||||
heading_text: str_field_or_empty(&o, "headingText"),
|
||||
rect,
|
||||
viewport_width: vp("viewportWidth"),
|
||||
viewport_height: vp("viewportHeight"),
|
||||
};
|
||||
findings_to_js(&measures::check_oversized_h1(&input))
|
||||
}
|
||||
"checkGptThinBorderWideShadow" => {
|
||||
let o = arg(0);
|
||||
let widths: Vec<f64> = match field(&o, "borderWidths") {
|
||||
Some(Js::Arr(items)) => items.iter().map(to_number).collect(),
|
||||
_ => return None,
|
||||
};
|
||||
let colors: Option<Vec<Option<String>>> = match field(&o, "borderColors") {
|
||||
Some(Js::Arr(items)) => Some(
|
||||
items
|
||||
.iter()
|
||||
.map(|c| match c {
|
||||
Js::Str(s) => Some(s.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
_ => None,
|
||||
};
|
||||
let input = measures::GptBorderShadowInput {
|
||||
border_widths: &widths,
|
||||
border_colors: colors.as_deref(),
|
||||
box_shadow: str_field(&o, "boxShadow"),
|
||||
};
|
||||
findings_to_js(&measures::check_gpt_thin_border_wide_shadow(&input))
|
||||
}
|
||||
"checkContentHiddenAtRest" => {
|
||||
let o = arg(0);
|
||||
let n = |key: &str| match field(&o, key) {
|
||||
None | Some(Js::Undef) => 0.0,
|
||||
Some(v) => to_number(v),
|
||||
};
|
||||
let samples: Vec<String> = match field(&o, "hiddenSamples") {
|
||||
Some(Js::Arr(items)) => items
|
||||
.iter()
|
||||
.map(|s| match s {
|
||||
Js::Str(s) => s.clone(),
|
||||
other => match encode(other) {
|
||||
Value::String(s) => s,
|
||||
v => v.to_string(),
|
||||
},
|
||||
})
|
||||
.collect(),
|
||||
_ => vec![],
|
||||
};
|
||||
let input = measures::ContentHiddenInput {
|
||||
total_chars: n("totalChars"),
|
||||
hidden_chars: n("hiddenChars"),
|
||||
hidden_samples: samples,
|
||||
};
|
||||
findings_to_js(&measures::check_content_hidden_at_rest(&input))
|
||||
}
|
||||
"isCreamColor" => Js::Bool(measures::is_cream_color(rgba_from(&arg(0)).as_ref())),
|
||||
"isKickerCandidate" => {
|
||||
let o = arg(0);
|
||||
let input = text_rules::KickerCandidateInput {
|
||||
heading_level: num_field(&o, "headingLevel"),
|
||||
heading_text: str_field_or_empty(&o, "headingText"),
|
||||
heading_font_size: num_field(&o, "headingFontSize"),
|
||||
kicker_tag: str_field_or_empty(&o, "kickerTag"),
|
||||
kicker_text: str_field_or_empty(&o, "kickerText"),
|
||||
kicker_text_transform: str_field_or_empty(&o, "kickerTextTransform"),
|
||||
kicker_font_variant: str_field_or_empty(&o, "kickerFontVariant"),
|
||||
kicker_font_size: num_field(&o, "kickerFontSize"),
|
||||
kicker_letter_spacing: num_field(&o, "kickerLetterSpacing"),
|
||||
};
|
||||
Js::Bool(text_rules::is_kicker_candidate(&input))
|
||||
}
|
||||
"isNumberedSectionLabelCandidate" => {
|
||||
let o = arg(0);
|
||||
let label_index = match field(&o, "labelIndex") {
|
||||
None | Some(Js::Undef) | Some(Js::Null) => None,
|
||||
Some(v) => Some(to_number(v)),
|
||||
};
|
||||
let weight_str;
|
||||
let label_font_weight = match field(&o, "labelFontWeight") {
|
||||
Some(Js::Str(s)) => s.as_str(),
|
||||
Some(Js::Num(n)) => {
|
||||
weight_str = js::number_to_string(*n);
|
||||
weight_str.as_str()
|
||||
}
|
||||
_ => "",
|
||||
};
|
||||
let input = text_rules::NumberedLabelCandidateInput {
|
||||
heading_tag: str_field_or_empty(&o, "headingTag"),
|
||||
heading_text: str_field_or_empty(&o, "headingText"),
|
||||
heading_font_size: num_field(&o, "headingFontSize"),
|
||||
label_tag: str_field_or_empty(&o, "labelTag"),
|
||||
label_index,
|
||||
label_text: str_field_or_empty(&o, "labelText"),
|
||||
label_font_size: num_field(&o, "labelFontSize"),
|
||||
label_letter_spacing: num_field(&o, "labelLetterSpacing"),
|
||||
label_font_weight,
|
||||
label_font_family: str_field_or_empty(&o, "labelFontFamily"),
|
||||
label_text_transform: str_field_or_empty(&o, "labelTextTransform"),
|
||||
label_color: str_field_or_empty(&o, "labelColor"),
|
||||
};
|
||||
Js::Bool(text_rules::is_numbered_section_label_candidate(&input))
|
||||
}
|
||||
"checkNumberedSectionLabels" => {
|
||||
let o = arg(0);
|
||||
let candidates: Vec<text_rules::NumberedLabelCandidate> = match field(&o, "candidates")
|
||||
{
|
||||
Some(Js::Arr(items)) => items
|
||||
.iter()
|
||||
.map(|c| text_rules::NumberedLabelCandidate {
|
||||
index: num_field(c, "index"),
|
||||
label_text: str_field_or_empty(c, "labelText").to_string(),
|
||||
heading_tag: str_field_or_empty(c, "headingTag").to_string(),
|
||||
heading_text: str_field_or_empty(c, "headingText").to_string(),
|
||||
})
|
||||
.collect(),
|
||||
_ => return Some(Value::Array(vec![])),
|
||||
};
|
||||
let min_count = match field(&o, "minCount") {
|
||||
None | Some(Js::Undef) => None,
|
||||
Some(v) => Some(to_number(v)),
|
||||
};
|
||||
findings_to_js(&text_rules::check_numbered_section_labels(
|
||||
&candidates,
|
||||
min_count,
|
||||
))
|
||||
}
|
||||
"checkEmDashOveruse" => {
|
||||
let t = arg(0);
|
||||
findings_to_js(&text_rules::check_em_dash_overuse(opt_str(&t)))
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
Some(encode(&result))
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
//! impeccable-core: the rule logic of the impeccable detector engine, ported
|
||||
//! from the JS `cli/engine` with byte-for-byte behavioral parity. The
|
||||
//! `check_*` / `scan_*` functions and the heuristics behind them live here.
|
||||
//!
|
||||
//! Everything they are written against lives in `impeccable-foundation`: JS
|
||||
//! number and string semantics, colour maths, the rule registry, inline
|
||||
//! ignores, the DOM probe trait, and the plain-data input and output types.
|
||||
//! This crate re-exports those modules for its own convenience, so
|
||||
//! `crate::js`, `crate::color`, `crate::browser::dom` and friends keep
|
||||
//! resolving inside it, and so consumers can name everything through
|
||||
//! `impeccable_core::`. No filesystem, process, or network access lives here,
|
||||
//! and the crate compiles to wasm (`crates/wasm` builds the in-page bundle
|
||||
//! and the extension core from it).
|
||||
|
||||
pub mod browser;
|
||||
pub mod checks;
|
||||
|
||||
pub use impeccable_foundation::{
|
||||
color, constants, fdlibm_trig, findings, fonts, inline_ignores, js, js_ext_a, js_ext_b, page,
|
||||
registry, rule_pack,
|
||||
};
|
||||
|
||||
#[cfg(any(test, feature = "vectors"))]
|
||||
pub mod vectors;
|
||||
@@ -0,0 +1,35 @@
|
||||
//! Replay dispatcher for the recorded JS call vectors
|
||||
//! (`tests/oracle/vectors/calls/<module>/<fn>.jsonl`).
|
||||
//!
|
||||
//! The codec and the arms for the helper modules live in
|
||||
//! [`impeccable_foundation::vectors`]; this module re-exports them and adds
|
||||
//! this crate's own arms, so one `call` reaches every ported function and
|
||||
//! `KNOWN_FUNCTIONS` is the union of both id tables.
|
||||
|
||||
use once_cell::sync::Lazy;
|
||||
use serde_json::Value;
|
||||
|
||||
pub use impeccable_foundation::vectors::{decode, encode, Js};
|
||||
|
||||
/// Every `(module, [function, ...])` the dispatcher answers: foundation's
|
||||
/// arms plus this crate's.
|
||||
pub static KNOWN_FUNCTIONS: Lazy<Vec<(&'static str, &'static [&'static str])>> = Lazy::new(|| {
|
||||
let mut rows: Vec<(&'static str, &'static [&'static str])> =
|
||||
impeccable_foundation::vectors::KNOWN_FUNCTIONS.to_vec();
|
||||
rows.extend_from_slice(crate::checks::vectors_a::KNOWN);
|
||||
rows.extend_from_slice(crate::checks::vectors_b::KNOWN);
|
||||
rows
|
||||
});
|
||||
|
||||
/// Invoke the Rust port of `<module>.<fn_name>` with recorder-encoded
|
||||
/// arguments; returns the recorder-encoded result, or `None` when the
|
||||
/// function is not known to the dispatcher.
|
||||
pub fn call(module: &str, fn_name: &str, args: &[Value]) -> Option<Value> {
|
||||
if let Some(v) = impeccable_foundation::vectors::call(module, fn_name, args) {
|
||||
return Some(v);
|
||||
}
|
||||
if let Some(v) = crate::checks::vectors_a::call(module, fn_name, args) {
|
||||
return Some(v);
|
||||
}
|
||||
crate::checks::vectors_b::call(module, fn_name, args)
|
||||
}
|
||||
Reference in New Issue
Block a user